Skip to content

Commit 876a527

Browse files
committed
feat: 0121.Best Time to Buy and Sell Stock
1 parent 0b0e4ce commit 876a527

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ description: "0121.Best-Time-to-Buy-and-Sell-Stock"
1010
license: ""
1111
images: []
1212

13-
tags: [LeetCode, Go, Easy, Slide Windows, DP, Best Time to Buy and Sell Stock, array, Blind75]
13+
tags: [LeetCode, Go, Easy, Slide Windows, DP, Best Time to Buy and Sell Stock, array, Blind75,amazon, bloomberg, facebook, microsoft, uber]
1414
categories: [LeetCode]
1515

1616
featuredImage: ""
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// 時間複雜度:
2+
// 空間複雜度:
3+
/*
4+
* @lc app=leetcode.cn id=121 lang=golang
5+
*
6+
* [121] 买卖股票的最佳时机
7+
*
8+
* https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/
9+
*
10+
* algorithms
11+
* Easy (57.70%)
12+
* Likes: 3468
13+
* Dislikes: 0
14+
* Total Accepted: 1.4M
15+
* Total Submissions: 2.4M
16+
* Testcase Example: '[7,1,5,3,6,4]'
17+
*
18+
* 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
19+
*
20+
* 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
21+
*
22+
* 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
23+
*
24+
*
25+
*
26+
* 示例 1:
27+
*
28+
*
29+
* 输入:[7,1,5,3,6,4]
30+
* 输出:5
31+
* 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
32+
* ⁠ 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
33+
*
34+
*
35+
* 示例 2:
36+
*
37+
*
38+
* 输入:prices = [7,6,4,3,1]
39+
* 输出:0
40+
* 解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
41+
*
42+
*
43+
*
44+
*
45+
* 提示:
46+
*
47+
*
48+
* 1
49+
* 0
50+
*
51+
*
52+
*/
53+
54+
// @lc code=start
55+
func maxProfit(prices []int) int {
56+
if len(prices) < 1 {
57+
return 0
58+
}
59+
minPrice := prices[0]
60+
maxProfit := 0
61+
for i := 1; i < len(prices); i++ {
62+
if prices[i] < minPrice {
63+
minPrice = prices[i]
64+
} else {
65+
profit := prices[i] - minPrice
66+
if profit > maxProfit {
67+
maxProfit = profit
68+
}
69+
}
70+
}
71+
return maxProfit
72+
}
73+
74+
// @lc code=end
75+

0 commit comments

Comments
 (0)