https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/
dp
注释掉了dp数组,因为在某个用例时会超出内存。所以只用变量表示。
class Solution {
public int maxProfit(int[] prices) {
int len=prices.length;
if(len==1) return 0;
//int[][] dp=new int[len][len];//最大利润
//[i][0]在今天不持有股票
//[i][1]在今天持有股票
//在同一天出售,没有任何意义啊,又没有差价
//dp[0][0]=0;
//dp[0][1]=-prices[0];
int a=0,b=-prices[0];
int max=0;//最大利润初始化为0
for(int i=1;i<len;i++){
//今天不持有:昨天不持有;昨天持有但今天卖掉了
//dp[i][0]=Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
int c=Math.max(a,b+prices[i]);
//今天持有:昨天就持有;昨天没有但是今天买了
//dp[i][1]=Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
int d=Math.max(b,a-prices[i]);
max=Math.max(max,Math.max(c,d));
a=c;
b=d;
}
return max;
}
}
贪心
把利润分为每一天。每天只收集正利润。
// 贪心思路
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for (int i = 1; i < prices.length; i++) {
result += Math.max(prices[i] - prices[i - 1], 0);
}
return result;
}
}