@@ -40,7 +40,7 @@ Explanation: In this case, no transaction is done, i.e. max profit = 0.
40
40
41
41
## 代码
42
42
43
- 语言支持:JS,Python,C++
43
+ 语言支持:JS,Python,C++
44
44
45
45
JS Code:
46
46
@@ -60,31 +60,31 @@ JS Code:
60
60
*
61
61
* Say you have an array for which the i^th element is the price of a given
62
62
* stock on day i.
63
- *
63
+ *
64
64
* If you were only permitted to complete at most one transaction (i.e., buy
65
65
* one and sell one share of the stock), design an algorithm to find the
66
66
* maximum profit.
67
- *
67
+ *
68
68
* Note that you cannot sell a stock before you buy one.
69
- *
69
+ *
70
70
* Example 1:
71
- *
72
- *
71
+ *
72
+ *
73
73
* Input: [7,1,5,3,6,4]
74
74
* Output: 5
75
75
* Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit
76
76
* = 6-1 = 5.
77
77
* Not 7-1 = 6, as selling price needs to be larger than buying price.
78
- *
79
- *
78
+ *
79
+ *
80
80
* Example 2:
81
- *
82
- *
81
+ *
82
+ *
83
83
* Input: [7,6,4,3,1]
84
84
* Output: 0
85
85
* Explanation: In this case, no transaction is done, i.e. max profit = 0.
86
- *
87
- *
86
+ *
87
+ *
88
88
*/
89
89
/**
90
90
* @param {number[]} prices
@@ -111,28 +111,19 @@ var maxProfit = function(prices) {
111
111
Python Code:
112
112
113
113
``` python
114
- # 应用Kadane's algorithms
115
114
class Solution :
116
115
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
- """
116
+ if not prices: return 0
117
+
118
+ min_price = float (' inf' )
119
+ max_profit = 0
120
+
121
+ for price in prices:
122
+ if price < min_price:
123
+ min_price = price
124
+ elif max_profit < price - min_price:
125
+ max_profit = price - min_price
126
+ return max_profit
136
127
```
137
128
138
129
C++ Code:
@@ -164,4 +155,3 @@ public:
164
155
165
156
- [122.best-time-to-buy-and-sell-stock-ii](./122.best-time-to-buy-and-sell-stock-ii.md)
166
157
- [309.best-time-to-buy-and-sell-stock-with-cooldown](./309.best-time-to-buy-and-sell-stock-with-cooldown.md)
167
-
0 commit comments