Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Subscribe to see which companies asked this question
解法2 动态规划:股票必须先买后卖。对于某一天,股票手上的股票只有两种状态,sell和buy;因为最终手里面没有股票,最终需要的结果是sell.既手里股票卖了获得最大利润。所以我们可以用两个dp数组分别记录当前持有股票和未持有股票的状态。从而理清二者的转换条件。
对于当天最终未持有股票。最终最大利润有两种可能,一是今天没做任何操作,跟昨天未持有股票状态一样。第二是昨天此股了,今天卖了。最大利润取二者之间的最大值即可。表达式如下 : selldp[i] = Math.max(selldp[i-1], buydp[i-1]+prices[i]);
对于当天持有股票,最大利润也是有两种, 一是今天跟昨天一样,持有股票。二是昨天未持有股票, 今天买入了股票。最大利润取二者最大值即可。表达式如下:buydp[i]=Math.max(buydp[i], selldp[i-1]-prices[i])
最终结果为selldp[n-1] : 表示为最后一天结束时候手里没有股票积累的最大利润。
代码如下:
<span style="font-size:14px;">public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0){
return 0;
}
int[] buydp = new int[prices.length];
int[] selldp = new int[prices.length];
buydp[0] = -prices[0];
selldp[0] = 0;
for(int i = 1; i < prices.length; i++){
selldp[i] = Math.max(selldp[i-1], buydp[i-1] + prices[i]);
buydp[i] = Math.max(buydp[i-1], selldp[i-1] - prices[i]);
}
return selldp[prices.length - 1];
}
}</span>