方法一 动态规划
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
int dp[size][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i = 1; i < size; i++){
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[size - 1][0];
}
};
Accepted 200/200 cases passed (0 ms) Your runtime beats 100 % of cpp submissions Your memory usage beats 24.93 % of cpp submissions (12.8 MB)
方法二 贪心
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
int ans = 0;
for(int i = 1; i < size; i++){
ans += max(0, prices[i] - prices[i - 1]);
}
return ans;
}
};
Accepted 200/200 cases passed (8 ms) Your runtime beats 47.64 % of cpp submissions Your memory usage beats 89.67 % of cpp submissions (12.6 MB)
|