Skip to content

Commit 880d092

Browse files
committed
Adding Efficient Solution - Problem - 122 - Best Time Buy Sell Stock II
1 parent 1abe274 commit 880d092

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 122
6+
## Problem Name: Best Time to Buy and Sell Stock II
7+
##===================================
8+
#
9+
#Say you have an array prices for which the ith element is the price of a given stock on day i.
10+
#
11+
#Design an algorithm to find the maximum profit.
12+
#You may complete as many transactions as you like
13+
#(i.e., buy one and sell one share of the stock multiple times).
14+
#
15+
#Note: You may not engage in multiple transactions at the same time
16+
#(i.e., you must sell the stock before you buy again).
17+
#
18+
#Example 1:
19+
#
20+
#Input: [7,1,5,3,6,4]
21+
#Output: 7
22+
#Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
23+
# Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
24+
#Example 2:
25+
#
26+
#Input: [1,2,3,4,5]
27+
#Output: 4
28+
#Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
29+
# Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
30+
# engaging multiple transactions at the same time. You must sell before buying again.
31+
#Example 3:
32+
#
33+
#Input: [7,6,4,3,1]
34+
#Output: 0
35+
#Explanation: In this case, no transaction is done, i.e. max profit = 0.
36+
class Solution:
37+
def maxProfit(self, prices):
38+
tmp = 0 #Initialze tmp
39+
for i in range(1, len(prices)): #Loop through prices from 1 to prices
40+
if prices[i - 1] < prices[i]: #Condition-check: If price[i-1] is less than price[i]
41+
tmp += (prices[i] - prices[i-1]) #We update tmp by adding tmp and difference of price from i to i-1 untill we reach the end of array
42+
return tmp #We return tmp which is max Profit

0 commit comments

Comments
 (0)