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.
10
+
#
11
+
#If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
12
+
#
13
+
#Note that you cannot sell a stock before you buy one.
14
+
#
15
+
#Example 1:
16
+
#
17
+
#Input: [7,1,5,3,6,4]
18
+
#Output: 5
19
+
#Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
20
+
# Not 7-1 = 6, as selling price needs to be larger than buying price.
21
+
#Example 2:
22
+
#
23
+
#Input: [7,6,4,3,1]
24
+
#Output: 0
25
+
#Explanation: In this case, no transaction is done, i.e. max profit = 0.
26
+
classSolution:
27
+
defmaxProfits(self, prices):
28
+
ifprices== []: #Condition-check: If prices is empty list
29
+
return0#Return 0
30
+
tmp, min=0, prices[0] #Initialize tmp and min which is 0 and first element of the list respectively
31
+
foriinrange(1, len(prices)): #Loop through prices
32
+
ifprices[i] <min: #Condition-check: If prices is less thatn min
33
+
min=prices[i] #We update min by set to prices[i]
34
+
else: #Condition-check: Else
35
+
tmp=max(tmp, prices[i] -min) #Update tmp by taking max of tmp and difference of prices[i] and min
0 commit comments