一个团灭6道股票的题解,状态机,三维dp
121. 买卖股票的最佳时机
class Solution {
public int maxProfit(int[] prices) {
if(prices.length<1) return 0;
int min=Integer.MAX_VALUE;
int ret=0;
for(int i=0;i<prices.length;i++){
//不断的找到最低点
if(prices[i]<min){
min=prices[i];
//找到最大利润
}else if(ret<prices[i]-min){
ret=prices[i]-min;
}
}
return ret;
}
}
122. 买卖股票的最佳时机 II
第一种方法:dp
class Solution {
public int maxProfit(int[] prices) {
int dp[] =new int[prices.length+1];
//dp[n]表示前n个的最大利润
dp[0]=0;
for(int i=0;i<prices.length;i++){
int max=dp[i];
for(int j=i-1;j>=0;j--){
if(prices[i]>prices[j]){
int maxt=prices[i]-prices[j];
if (j-1>=0) {
maxt+=dp[j];
}
max=Math.max(maxt,max);
}
}
dp[i+1]=max;
}
return dp[prices.length];
}
}
第二种方法:官方题解(看来还是要学会分析呀)
public int maxProfit(int[] prices) {
int maxprofit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1])
maxprofit += prices[i] - prices[i - 1];
}
return maxprofit;
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0) return 0;
int [][][]dp=new int[prices.length][2][2];
//dp[i][j][k]表示 第i天 最多允许交易数j+1 不持有股票(k=0),持有股票(k=1),的最大利润
//初始化
dp[0][0][0]=0;
dp[0][1][0]=0;
dp[0][0][1]=-prices[0];
dp[0][1][1]=-prices[0];
for(int i=1;i<prices.length;i++){
//今天的状态来源:可能昨天什么都不做,也有可能是昨天股票卖出去
dp[i][1][0]=Math.max(dp[i-1][1][0],dp[i-1][1][1]+prices[i]);
dp[i][1][1]=Math.max(dp[i-1][1][1],dp[i-1][0][0]-prices[i]);
dp[i][0][0]=Math.max(dp[i-1][0][0],dp[i-1][0][1]+prices[i]);
//今天的状态来源:可能昨天什么都不做,也有可能是昨天股票买进来
dp[i][0][1]=Math.max(dp[i-1][0][1],-prices[i]);
}
return dp[prices.length-1][1][0];
}
}