Skip to content

Commit 6458a76

Browse files
committed
121.best_time_to_buy_and_sell_stock
1 parent f534e01 commit 6458a76

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package data_structures_algorithms
2+
3+
func maxProfit(prices []int) int {
4+
if len(prices) <= 1 {
5+
return 0
6+
}
7+
min, maxProfit := prices[0], 0
8+
for i := 1; i < len(prices); i++ {
9+
if prices[i]-min > maxProfit {
10+
maxProfit = prices[i] - min
11+
}
12+
if prices[i] < min {
13+
min = prices[i]
14+
}
15+
}
16+
return maxProfit
17+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# [121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
2+
You are given an array `prices` where `prices[i]` is the price of a given stock on the <code>i<sup>th</sup></code> day.
3+
4+
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
5+
6+
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return `0`.
7+
8+
#### Example 1:
9+
```shell
10+
Input: prices = [7,1,5,3,6,4]
11+
Output: 5
12+
```
13+
14+
#### Example 2:
15+
```shell
16+
Input: prices = [7,6,4,3,1]
17+
Output: 0
18+
```
19+
20+
<br>
21+
22+
#### Constraints:
23+
- <code>1 <= prices.length <= 10<sup>5</sup></code>
24+
- <code>0 <= prices[i] <= 10<sup>4</sup></code>

0 commit comments

Comments
 (0)