LeetCode 122. 买卖股票的最佳时机 II

题目描述

122. 买卖股票的最佳时机 II

image-20250510111559095

image-20250510111615341

思路分析

这道题目是经典的股票交易问题,其主要目的是利用多次交易获得最大利润。

相比于第一题(只能买卖一次),这道题可以进行无限次交易,但有一个限制:必须先卖出再买入。

image-20250510111834362

参考代码

1
2
3
4
5
6
7
8
9
10
func maxProfit(prices []int) int {
	var res int
	for i := 1; i < len(prices); i++ {
		// 如果今天的价格比昨天高,说明可以交易
		if prices[i] > prices[i-1] {
			res += prices[i] - prices[i-1]
		}
	}
	return res
}
1
write your code here

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/91892556
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!