Skip to content

Commit aab2290

Browse files
committed
最值: 股票最大值
Change-Id: I70501fe02d4b5b40c6cd877e82f3fc090bbaf18f
1 parent cbbad59 commit aab2290

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* @lc app=leetcode.cn id=121 lang=golang
3+
*
4+
* [121] 买卖股票的最佳时机
5+
*
6+
* https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
7+
*
8+
* algorithms
9+
* Easy (50.14%)
10+
* Likes: 442
11+
* Dislikes: 0
12+
* Total Accepted: 54.1K
13+
* Total Submissions: 107.8K
14+
* Testcase Example: '[7,1,5,3,6,4]'
15+
*
16+
* 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
17+
*
18+
* 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
19+
*
20+
* 注意你不能在买入股票前卖出股票。
21+
*
22+
* 示例 1:
23+
*
24+
* 输入: [7,1,5,3,6,4]
25+
* 输出: 5
26+
* 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
27+
* ⁠ 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
28+
*
29+
*
30+
* 示例 2:
31+
*
32+
* 输入: [7,6,4,3,1]
33+
* 输出: 0
34+
* 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
35+
*
36+
*
37+
*/
38+
39+
// 假设买点在第一天,后面发现如果有更低的,就更新买点。
40+
// 在发现更低买点的时候,是不可能在这个时候卖出的,所以最大利润是昨天的利润
41+
// 遍历下来,不断更新买点和比较最大利润,就可以得到结果
42+
func maxProfit(prices []int) int {
43+
if len(prices) <= 0 {
44+
return 0
45+
}
46+
buy := prices[0]
47+
res := 0
48+
for i := 1; i < len(prices); i++ {
49+
if prices[i] < buy {
50+
buy = prices[i]
51+
}
52+
tmp := prices[i] - buy
53+
if tmp > res {
54+
res = tmp
55+
}
56+
}
57+
return res
58+
}
59+

0 commit comments

Comments
 (0)