Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions BuyAndSell2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Time Complexity : O(n)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
profit = 0
i = 0
while i < len(prices):

while i < len(prices)-1 and prices[i+1] <= prices[i]:
i += 1
min_ = prices[i]
i += 1

while i < len(prices)-1 and prices[i+1] >= prices[i]:
i+= 1

if i < len(prices):
profit += prices[i] - min_
i += 1

return profit
43 changes: 43 additions & 0 deletions PeekingIterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class PeekingIterator:
temp = None
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.itr = iterator
if self.itr.hasNext():
self.temp = self.itr.next()

# Time = O(1) | Space = O(1)
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.temp

# Time = O(1) | Space = O(1)
def next(self):
"""
:rtype: int
"""
prev = self.temp
if self.itr.hasNext():
self.temp = self.itr.next()
else:
self.temp = None
return prev

# Time = O(1) | Space = O(1)
def hasNext(self):
"""
:rtype: bool
"""
if self.temp is not None :
return True
else:
return False