11.08每日一题
122. 买卖股票的最佳时机 II
首先阅读题目得知可以做的动作有两个买或者卖,并且不能参与多笔交易,状态只可能是有1支股票或者没有股票,所以动态规划方程每一天有两个状态,每一天的状态从前一天转移有两种可能,如果当前没有股票(dp[i][0])说明前一天没有股票dp[i-1][0]或者前一天有股票但是今天卖掉了(dp[i-1][1]+price(i)),如果当前有股票(dp[i][1])说明前一天有股票(dp[i-1][1])或者前一天没有股票买进了股票(dp[i-1][0]-price(i)),为了收益最大化就是求max。
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int[][] dp = new int[prices.length][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i = 0; i < prices.length; i++){
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1]= Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[prices.length - 1][0];
}
}
从上面的代码中可以看出,转移方程除了前一天其他的都没有关系,所以进行空间优化。
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int dp0 = 0;
int dp1 = -prices[0];
for(int i = 0; i < prices.length; i++){
dp0 = Math.max(dp0, dp1 + prices[i]);
dp1 = Math.max(dp1, dp0 - prices[i]);
}
return dp0;
}
}
这道题还可以进行贪心,只要每两天股价上涨就加上,下降就不计入。
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1; i < prices.length; i++){
res += Math.max(0, prices[i] - prices[i - 1]);
}
return res;
}
}