题解 | #买卖股票的最好时机(三)#

买卖股票的最好时机(三)

http://www.nowcoder.com/practice/4892d3ff304a4880b7a89ba01f48daf9



public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 两次交易所能获得的最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        if(prices.length == 0) return 0;
        int first_hold=-prices[0],second_hold=-prices[0];
        int first_sell=0,second_sell=0;
        for(int i=1;i<prices.length;i++){
             first_hold = Math.max(first_hold,-prices[i]);
             first_sell = Math.max(first_sell,first_hold+prices[i]);
             
            second_hold = Math.max(second_hold,first_sell-prices[i]);
            second_sell = Math.max(second_sell,second_hold + prices[i]);
         }
        return second_sell;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务