股票利润最大化--2 算法详解


package com.leetcode.practice.demo150;

public class Demo1majorityElement2 {
    public static void main(String[] args) {
        int res = new Demo1majorityElement2().maxProfit(new int[] { 2, 4, 1 });
        System.out.println(res);
    }

    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        int profitSum = 0;
        for (int i = 0; i < prices.length; i++) {
            // 获取新交易起点最小价格
            if (prices[i] < minPrice) {
                minPrice = prices[i];
                // 如果当前有利润,则将利润加入到总利润中
                // 处理:1,3,0这种情况
                if (maxProfit != 0) {
                    profitSum += maxProfit;
                    maxProfit = 0;
                }
            } else if (prices[i] - minPrice > maxProfit) {
                // 如果当前价格减去最小价格大于最大利润,则更新最大利润
                maxProfit = prices[i] - minPrice;
            } else {
                // 如果当前价格减去最小价格小于最大利润,则将利润加入到总利润中
                // 处理,1,2,5,2的这种情况
                minPrice = prices[i];
                profitSum += maxProfit;
                maxProfit = 0;
            }
        }

        // 如果总利润为0,则将最大利润加入到总利润中
        if (profitSum == 0 || maxProfit != 0) { // 条件2,处理一直增加的情况
            profitSum += maxProfit;
        }
        return profitSum;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值