题目链接:121. 买卖股票的最佳时机
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) {
return 0;
}
int min = prices[0];
int dpCur;
int dpMax = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] - min > 0) {
dpCur = prices[i] - min;
dpMax = Math.max(dpMax, dpCur);
}
min = Math.min(min, prices[i]);
}
return dpMax;
}
}
题目链接:122. 买卖股票的最佳时机 II
class Solution {
public int maxProfit(int[] prices) {
int ans = 0;
int n = prices.length;
for (int i = 1; i < n; ++i) {
ans += Math.max(0, prices[i] - prices[i - 1]);
}
return ans;
}
}