We want to collect the maximum coins from a sequence, possibly with some constraints (not specified in the excerpt). If the problem is to collect the maximum sum of a contiguous subarray (like the classic maximum subarray problem), we can use Kadane’s algorithm. If there are additional constraints, the approach may need to be adjusted, but for the standard case, DP is optimal.
classSolution {
public:int maxCoins(vector<int>& coins) {
int ans = coins[0], cur = coins[0];
for (int i =1; i < coins.size(); ++i) {
cur = max(coins[i], cur + coins[i]);
ans = max(ans, cur);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintmaxCoins(int[] coins) {
int ans = coins[0], cur = coins[0];
for (int i = 1; i < coins.length; ++i) {
cur = Math.max(coins[i], cur + coins[i]);
ans = Math.max(ans, cur);
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
defmaxCoins(self, coins: list[int]) -> int:
ans = cur = coins[0]
for c in coins[1:]:
cur = max(c, cur + c)
ans = max(ans, cur)
return ans