121 买卖股票的最佳时机
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/
class Solution { //贪心?直观做法
public int maxProfit(int[] prices) {
int minPrice = prices[0];
int diff = 0;
for (int price : prices) {
if (price - minPrice > diff) {
diff = price - minPrice;
}
minPrice = Math.min(minPrice, price);
}
return diff;
}
}
class Solution { //DP
public int maxProfit(int[] prices) {
int hold = -prices[0];
int unhold = 0;
for (int i = 1; i < prices.length; i++) {
hold = Math.max(hold, -prices[i]); // 只能买一次体现在以前买的或者今天买的
unhold = Math.max(unhold, hold + prices[i]);
}
return unhold;
}
}
122 买卖股票的最佳时机II
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
class Solution { //贪心,收集正数的每天利润
public int maxProfit(int[] prices) {
int sum = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) sum += prices[i] - prices[i - 1];
}
return sum;
}
}
class Solution { //dp
public int maxProfit(int[] prices) {
int hold = -prices[0];
int unhold = 0;
for (int i = 1; i < prices.length; i++) {
int temp = hold;
hold = Math.max(hold, unhold - prices[i]);
unhold = Math.max(unhold, temp + prices[i]);
}
return unhold;
}
}