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;
}
}
股票利润最大化--2 算法详解
最新推荐文章于 2026-06-29 07:01:47 发布
590

被折叠的 条评论
为什么被折叠?



