Skip to content

Commit 1428578

Browse files
committed
Solution added.
1 parent 7b2dd67 commit 1428578

File tree

1 file changed

+28
-0
lines changed
  • 30 Days September Challange/Week 3/4. Best Time to Buy and Sell Stock

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""
2+
Say you have an array for which the ith element is the price of a given stock on day i.
3+
4+
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.
5+
6+
Note that you cannot sell a stock before you buy one.
7+
8+
Example 1:
9+
10+
Input: [7,1,5,3,6,4]
11+
Output: 5
12+
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
13+
Not 7-1 = 6, as selling price needs to be larger than buying price.
14+
Example 2:
15+
16+
Input: [7,6,4,3,1]
17+
Output: 0
18+
Explanation: In this case, no transaction is done, i.e. max profit = 0.
19+
"""
20+
class Solution:
21+
def maxProfit(self, prices: List[int]) -> int:
22+
buy,profit = sys.maxsize,-sys.maxsize-1
23+
for price in prices:
24+
if price <= buy:
25+
buy = price
26+
else:
27+
profit = max(profit,price-buy)
28+
return profit if profit > 0 else 0

0 commit comments

Comments
 (0)