动态规划练习:
根据每天的股票价值,设计算法以获取最大值。要求每天只能进行一种操作,买、卖、等待,只有买了之后才能且进行卖,不能连续买,卖了之后的一天必须等待什么都不能做。
思路:来源leetcode讨论区。 s0代表当前状态未持有股票。s1当前状态持有股票。s2当前状态因卖出股票未持有股票,不同与s0。
There are three states, according to the action that you can take.
Hence, from there, you can now the profit at a state at time i as:
s0[i] = max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1
Then, you just find the maximum of s0[n] and s2[n], since they will be the maximum profit we need (No one can buy stock and left with more profit that sell right :) )
Define base case:
s0[0] = 0; // At the start, you don't have any stock if you just rest
s1[0] = -prices[0]; // After buy, you should have -prices[0] profit. Be positive!
s2[0] = INT_MIN; // Lower base case
class Solution {
public int maxProfit(int[] prices) {
if (prices.length <= 1) return 0;
int n = prices.length;
int[] s0 = new int[n];
int[] s1 = new int[n];
int[] s2 = new int[n];
s1[0] = -prices[0];
s0[0] = 0;
s2[0] = Integer.MIN_VALUE;
for (int i = 1; i < prices.length; i++) {
s0[i] = Math.max(s0[i - 1], s2[i - 1]);
s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i]);
s2[i] = s1[i - 1] + prices[i];
}
return Math.max(s0[n - 1], s2[n - 1]);
}
}