【牛客】中國牛市

鏈接:https://www.nowcoder.com/questionTerminal/9370d298b8894f48b523931d40a9a4aa?orderByHotValue=0&query=%E9%A3%8E%E5%8F%A3%E7%9A%84%E7%8C%AA-%E4%B8%AD%E5%9B%BD%E7%89%9B%E5%B8%82&done=0&pos=1
來源:牛客網
 

[編程題]風口的豬-中國牛市

風口之下,豬都能飛。當今中國股市牛市,真可謂“錯過等七年”。 給你一個回顧歷史的機會,已知一支股票連續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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章