买卖股票的最佳时机 II
题目
122. 买卖股票的最佳时机 II - 力扣(LeetCode)
分析
如图为状态转移图,f[i]可以表示第一天买入,g[0]表示啥都不干。
题解
class Solution {public int maxProfit(int[] prices) {int n=prices.length;int[] f=new int[n+1];int[] g=new int[n+1];//f是买了股票后的最大值f[0]=-prices[0];g[0]=0;for(int i=1;i<=n;i++){f[i]=Math.max(f[i-1],g[i-1]-prices[i-1]);g[i]=Math.max(g[i-1],f[i-1]+prices[i-1]);}return g[n];}
}