Skip to content

Commit 34f9459

Browse files
author
luzhipeng
committed
2 parents 224aebc + ab50b14 commit 34f9459

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

problems/121.best-time-to-buy-and-sell-stock.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0.
4040

4141
## 代码
4242

43+
语言支持:JS,Python
44+
45+
JS Code:
46+
4347
```js
4448
/*
4549
* @lc app=leetcode id=121 lang=javascript
@@ -102,7 +106,41 @@ var maxProfit = function(prices) {
102106
};
103107
```
104108

109+
110+
111+
Python Code:
112+
113+
```python
114+
# 应用Kadane's algorithms
115+
class Solution:
116+
def maxProfit(self, prices: 'List[int]') -> int:
117+
"""
118+
step by step
119+
"""
120+
# error case
121+
if len(prices) < 1:
122+
return 0
123+
124+
# caluate the daily gains, break into a subarray problem
125+
gains = [prices[i]-prices[i-1] for i in range(1, len(prices))]
126+
127+
loc_max = global_max = 0 #not gains[0] in case of negative
128+
for i in range(len(gains)):
129+
loc_max = max(loc_max + gains[i], gains[i])
130+
if loc_max > global_max:
131+
global_max = loc_max
132+
"""
133+
Runtime: 48 ms, faster than 34.50% of Python3 online submissions for Best Time to Buy and Sell Stock.
134+
Memory Usage: 14.1 MB, less than 10.26% of Python3 online submissions for Best Time to Buy and Sell Stock.
135+
"""
136+
```
137+
138+
139+
140+
141+
105142
## 相关题目
143+
106144
- [122.best-time-to-buy-and-sell-stock-ii](./122.best-time-to-buy-and-sell-stock-ii.md)
107145
- [309.best-time-to-buy-and-sell-stock-with-cooldown](./309.best-time-to-buy-and-sell-stock-with-cooldown.md)
108146

problems/122.best-time-to-buy-and-sell-stock-ii.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0.
4949

5050
## 代码
5151

52+
语言支持:JS,Python
53+
54+
JS Code:
55+
5256
```js
5357

5458
/*
@@ -123,7 +127,26 @@ var maxProfit = function(prices) {
123127
};
124128
```
125129

130+
131+
132+
Python Code:
133+
134+
```python
135+
class Solution:
136+
def maxProfit(self, prices: 'List[int]') -> int:
137+
gains = [prices[i] - prices[i-1] for i in range(1, len(prices))
138+
if prices[i] - prices[i-1] > 0]
139+
return sum(gains)
140+
print(Solution().maxProfit([7, 1, 5, 3, 6, 4]))
141+
#评论区里都讲这是一道开玩笑的送分题.
142+
```
143+
144+
145+
146+
147+
126148
## 相关题目
149+
127150
- [121.best-time-to-buy-and-sell-stock](./121.best-time-to-buy-and-sell-stock.md)
128151
- [309.best-time-to-buy-and-sell-stock-with-cooldown](./309.best-time-to-buy-and-sell-stock-with-cooldown.md)
129152

0 commit comments

Comments
 (0)