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

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

https://www.nowcoder.com/practice/9e5e3c2603064829b0a0bbfca10594e9

package com.hhdd.dp;

/**
 * @Author huanghedidi
 * @Date 2022/8/7 17:11
 */
public class 买卖股票的最好时机2 {


    public static void main(String[] args) {
        int[] arr = {8, 9, 2, 5};
        int res = maxProfit(arr);
        System.out.println("res = " + res);
    }

    public static int maxProfit(int[] prices) {
        // write code here
        int ans = 0;
        // 标识是否购买
        boolean buyFlg = false;
        int buyPrice = Integer.MAX_VALUE;
        for (int i = 0; i < prices.length; i++) {
            if (i + 1 < prices.length) {
                // 预知明天的价格
                if (prices[i + 1] > prices[i] && !buyFlg) {
                    // 明天涨价 且没有买过 今天就得买
                    buyPrice = prices[i];
                    buyFlg = true;
                } else if (prices[i + 1] < prices[i] && buyFlg) {
                    // 明天降价 且买过 则得在今天卖掉
                    ans += prices[i] - buyPrice;
                    buyFlg = false;
                }
            } else {
                // 这里是最后一天的逻辑
                if (buyFlg) {
                    // 最后一天还持有,说明看好最后一天是涨价的
                    ans += prices[i] - buyPrice;
                    buyFlg = false;
                }
            }
        }
        return ans;
    }
}

全部评论

相关推荐

qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-05 15:27
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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