题解 | #牛群买卖计划#

牛群买卖计划

https://www.nowcoder.com/practice/3e4ae511b4a941b788da5077b08a7d07?tpId=354&tqId=10595790&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        int buy1 = Integer.MAX_VALUE;
        int buy2 = Integer.MAX_VALUE;
        int buy3 = Integer.MAX_VALUE;
        int sell1=0;int sell2=0;int sell3=0;
        for(int i=0;i<prices.length;i++){
            // 取最小购入
            buy1 = Math.min(buy1, prices[i]);
            // 最大卖出利润
            sell1 = Math.max(sell1, prices[i] - buy1);
            // 第一次买卖的基础上取最小购入
            buy2 = Math.min(buy2, prices[i] - sell1);
            // 取最大卖出
            sell2 = Math.max(sell2, prices[i] - buy2);
            // 在第二次买卖的基础上取最大利润
            buy3 = Math.min(buy3, prices[i] - sell2);
            sell3 = Math.max(sell3, prices[i] - buy3);;
        }
        return sell3;
    }
}

面试高频TOP202 文章被收录于专栏

面试高频TOP202题解

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-15 17:46
暑期就挂了,秋招还有机会吗
大聪明777:研发提前批,14号刚开的,官网上面的配图上有写。提前批没过的话,秋招还可以投,不过前面的笔试/面试记录会被保留,供秋招参考
26届校招投递进展
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务