-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimetoBuyandSellStock
More file actions
27 lines (22 loc) · 1.12 KB
/
BestTimetoBuyandSellStock
File metadata and controls
27 lines (22 loc) · 1.12 KB
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
#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.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
#maxDiff = 0
#for i in range(len(prices),0):
# for j in range(i, len(prices)):
# if prices[j] - prices[i] > maxDiff:
# maxDiff = prices[j] - prices[i]
#return maxDiff
#Above code works but takes too long
max_profit = 0
left_pointer = 0
right_pointer = 1
while right_pointer < len(prices):
if prices[right_pointer] - prices[left_pointer] > max_profit:
max_profit = prices[right_pointer] - prices[left_pointer]
if prices[right_pointer] < prices[left_pointer]:
left_pointer = right_pointer
right_pointer += 1
return max_profit