[編程題]風口的豬-中國牛市
風口之下,豬都能飛。當今中國股市牛市,真可謂“錯過等七年”。 給你一個回顧歷史的機會,已知一支股票連續n天的價格走勢,以長度爲n的整數數組表示,數組中第i個元素(prices[i])代表該股票第i天的股價。 假設你一開始沒有股票,但有至多兩次買入1股而後賣出1股的機會,並且買入前一定要先保證手上沒有股票。若兩次交易機會都放棄,收益爲0。 設計算法,計算你能獲得的最大收益。 輸入數值範圍:2<=n<=100,0<=prices[i]<=100
示例1
輸入
3,8,5,1,7,8
輸出
12
學習別人的思想
public class Main {
public int calculateMax(int[] prices) {
int firstBuy = Integer.MAX_VALUE;
int afterFirstSell = 0;
int afterSecondBuy = Integer.MIN_VALUE;
int afterSecondSell = 0;
for(int curPrice:prices){
//買入的價格越小越好
firstBuy = Math.min(firstBuy,curPrice);
//第一次賣出去的收益,越大越好
afterFirstSell = Math.max(afterFirstSell,curPrice-firstBuy);
//第二次買入後的收益,越大越好
afterSecondBuy = Math.max(afterSecondBuy,afterFirstSell-curPrice);
//第二次賣出去的收益,越大越好
afterSecondSell = Math.max(afterSecondSell,afterSecondBuy+curPrice);
}
return afterSecondSell;
}
}