Find the Maximum Number of Fruits Collected
Time complexity: $O(n^2)$
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
class Solution {
public:
int maxCollectedFruits(std::vector<std::vector<int>>& fruits) {
int n = fruits.size();
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += fruits[i][i];
fruits[i][i] = 0;
}
std::vector<int> dp(n + 2, 0x8000'0000);
std::vector<int> tmp(n + 2);
dp[n] = fruits[0].back();
for (int i = 1; i < n; ++i) {
std::swap(dp, tmp);
for (int j = 1; j <= n; ++j) {
dp[j] = std::max(std::max(tmp[j - 1], tmp[j]), tmp[j + 1]) + fruits[i][j - 1];
}
}
sum += dp[n];
std::fill(dp.begin(), dp.end(), 0x8000'0000);
dp[n] = fruits.back()[0];
for (int i = 1; i < n; ++i) {
std::swap(dp, tmp);
for (int j = 1; j <= n; ++j) {
dp[j] = std::max(std::max(tmp[j - 1], tmp[j]), tmp[j + 1]) + fruits[j - 1][i];
}
}
sum += dp[n];
return sum;
}
};
|
