-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path121_best_time_to_buy_and_sell_stock.py
78 lines (63 loc) · 2.36 KB
/
121_best_time_to_buy_and_sell_stock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
---
title: Best Time to Buy and Sell Stock
number: 121
difficulty: easy
tags: ['Array','Dynamic programming']
solved: true
---
"""
"""
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
"""
from typing import List
"""
Simple:
Find profit maximizing function
BUt its two pointers algorithm solution
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
return self.two_pointers(prices)
def two_pointers(self,prices:List[int])->int:
left,right = 0,1
max_profit = 0
while right < len(prices):
buy_price = prices[left]
sell_price = prices[right]
if buy_price < sell_price:
profit = sell_price-buy_price
max_profit = max(max_profit,profit)
else:
## Careful here we found minimum price
left = right
right+=1
return max_profit
def simple_efficient(self,prices:List[int])->int:
# nested two foor loops is inefficient
# lets slice array from current price to the future and get max value, instead of
max_profit = 0
for index_buy in range(len(prices)):
buy_price = prices[index_buy]
if index_buy+1 < len(prices):
max_sell_price = max(prices[index_buy+1:])
if max_sell_price > buy_price and max_sell_price-buy_price > max_profit:
max_profit = max_sell_price-buy_price
return max_profit
def simple(self,prices:List[int])-> int:
# lets try brute force
## works but TIME LIMIT EXCEEDED
max_profit = 0
for index_buy in range(len(prices)):
buy_price = prices[index_buy]
for index_sell in range(index_buy+1,len(prices)):
sell_price = prices[index_sell]
if sell_price > buy_price:
if sell_price -buy_price > max_profit:
max_profit = sell_price-buy_price
return max_profit
if __name__ == '__main__':
prices = [1,2,4,2,5,7,2,4,9,0,2]
print(Solution().maxProfit(prices))