Skip to content

Commit a4b7ab1

Browse files
committed
Adding Efficient Solution - Problem - 121 - Best Time Buy Sell Stock
1 parent cc5d1dd commit a4b7ab1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 121
6+
## Problem Name: Best Time to Buy and Sell Stock
7+
##===================================
8+
#
9+
#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+
class Solution:
27+
def maxProfits(self, prices):
28+
if prices == []: #Condition-check: If prices is empty list
29+
return 0 #Return 0
30+
tmp, min = 0, prices[0] #Initialize tmp and min which is 0 and first element of the list respectively
31+
for i in range(1, len(prices)): #Loop through prices
32+
if prices[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
36+
return tmp #We return tmp
37+

0 commit comments

Comments
 (0)