題目
P0764. 小可的糖果盒
思路
題目要求是貪心,但是個人覺得dp更有價效比
程式碼
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int min_candies(int n, int x, vector<int>& candies) {
vector<int> dp(n, 0);
dp[0] = max(0, candies[0] - x);
for (int i = 1; i < n; ++i) {
int total = candies[i] + candies[i-1];
if (total > x) {
int eat = total - x;
if (candies[i] >= eat) {
dp[i] = dp[i-1] + eat;
candies[i] -= eat;
} else {
dp[i] = dp[i-1] + candies[i];
candies[i] = 0;
}
} else {
dp[i] = dp[i-1];
}
}
return dp[n-1];
}
int main() {
int n, x;
cin >> n >> x;
vector<int> candies(n);
for (int i = 0; i < n; ++i) {
cin >> candies[i];
}
cout << min_candies(n, x, candies) << endl;
return 0;
}