风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100
解体思路:
考虑题目限制,至多卖出一次,买入可以1次/2次/0次,也就是低买高卖,计算max{第一次卖出-第一次买入}+max{第二次持有最高值-第二次买入},第二次可有可无,因此以第一次卖出为分界线,分别计算max{第一次卖出-第一次买入},右边计算max{第二次持有最高值-第二次买入};
代码:
public class Solution {
/**
* 计算你能获得的最大收益
*
* @param prices Prices[i]即第i天的股价
* @return 整型
*/
public int calculateMax(int[] prices) {
int[] lprofit=new int[prices.length];//存放max{第一次卖出-第一次买入}
int[] rprofit=new int[prices.length];//存放max{第二次持有最高值-第二次买入}
//从左到右循环
int maxProfit=0;//计算已有的最大收益
int minPrice=prices[0];//已经获得的最小值
for(int i=0;i<prices.length;i++){
if(minPrice>prices[i]){
minPrice=prices[i];
}
if(maxProfit< (prices[i]-minPrice)){//最大值产生比较
maxProfit=(prices[i]-minPrice);
}
lprofit[i]=maxProfit;
}
//从右到左循环
maxProfit=0;
rprofit[prices.length-1]=0;
int maxPrice = prices[prices.length-1];
minPrice=prices[prices.length-1];
int temp;
for(int j=(prices.length-2);j>=0;j-- ){
if(maxPrice<prices[j]){
maxPrice=prices[j];
}
if(maxProfit<(temp=maxPrice-prices[j])){
maxProfit=temp;
}
rprofit[j]=maxProfit;
}
//计算总和
maxProfit=0;
for(int i=0;i<prices.length;i++){
if((temp=lprofit[i]+rprofit[i]) >maxProfit ){
maxProfit=temp;
}
}
return maxProfit;
}
}