题目要求如下:
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) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]
算法思想:动态规划最重要的三个方面是找出动态规划的递推公式,边界条件的处理和使用,特定题目的特殊考虑。本题的递推公式是max=Max.max(max,precies[i]-prices[j]+dp[j-2])。
package cn.edu.bupt;
import java.util.Arrays;
public class BestTimeBuyandSellStockwithCooldown309 {
public int maxProfit(int[] prices) {
if(prices.length==0||prices==null){return 0;}
int[] dp=new int[prices.length+1];//定义存储最终结果的数组
Arrays.fill(dp, 0);//将数组的每一项初始化为0
for(int i=1;i<prices.length;i++)//遍历所给的浮动的价格数组
{
int max=0;//定义第i天所获得的最大利润
for(int j=0;j<i;j++)//从0开始遍历价格数组,一直到i为止,此时即是遍历
{
int temp=0;//处理边界条件,若所给价格天数达不到可以cooldown的地步,则只是计算相邻价格的差值
if(j-2<0){temp=0;}else{temp=j-2;}
max=Math.max(max, prices[i]-prices[j]+dp[temp]);//从每个j开始求其到i的 收益值
}
dp[i]=max;
if(dp[i]<dp[i-1]){dp[i]=dp[i-1];}//考虑本题的特殊性,如果收益小于昨天的,那今天就不做买卖操作。
}
//return dp[prices.length];
return dp[prices.length-1];
}
public static void main(String[] args) {
BestTimeBuyandSellStockwithCooldown309 bt309=new BestTimeBuyandSellStockwithCooldown309();
int[] prices=new int[]{};
System.out.println(bt309.maxProfit(prices));
}
}