You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Say you have an array for which the ith element is the price of a given stock on day i.
4
+
5
+
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
6
+
7
+
Example 1:
8
+
Input: [7, 1, 5, 3, 6, 4]
9
+
Output: 5
10
+
11
+
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
12
+
Example 2:
13
+
Input: [7, 6, 4, 3, 1]
14
+
Output: 0
15
+
16
+
In this case, no transaction is done, i.e. max profit = 0.
17
+
18
+
"""
19
+
20
+
"""my solution
21
+
直接超时
22
+
"""
23
+
classSolution(object):
24
+
defmaxProfit(self, prices):
25
+
"""
26
+
:type prices: List[int]
27
+
:rtype: int
28
+
"""
29
+
max=0
30
+
foriinrange(0,len(prices)-1):
31
+
forjinrange(i+1,len(prices)):
32
+
ifprices[j] -prices[i] >max:
33
+
max=prices[j] -prices[i]
34
+
returnmax
35
+
36
+
"""
37
+
Kadane's Algorithm
38
+
"""
39
+
40
+
classSolution(object):
41
+
defmaxProfit(self, prices):
42
+
"""
43
+
:type prices: List[int]
44
+
:rtype: int
45
+
"""
46
+
maxCur=maxSoFar=0
47
+
foriinrange(1,len(prices)):
48
+
maxCur+=(prices[i]-prices[i-1])
49
+
maxCur=max(0,maxCur)
50
+
maxSoFar=max(maxCur,maxSoFar)
51
+
returnmaxSoFar
Collapse file: easy/122_Best Time to Buy and Sell Stock II.py
Say you have an array for which the ith element is the price of a given stock on day i.
4
+
5
+
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
0 commit comments