EasySliding Window
Best Time to Buy and Sell Stock
Find max profit from one transaction
Solution Approach
Make locally optimal choices at each step. Choose the best option available at current state without reconsidering past choices. Works when problem has optimal substructure.
Implementation
def canJump(nums):
max_reach = 0
for i in range(len(nums)):
if i > max_reach:
return False
max_reach = max(max_reach, i + nums[i])
if max_reach >= len(nums) - 1:
return True
return FalseComplexity Analysis
Time Complexity
O(n)Space Complexity
O(1)Key Learning Points
Local optimal choicesNo backtracking neededTrack maximum reachable index
Related Problems to Practice
Jump GameJump Game IIBest Time to Buy Stock
Complexity
Time:O(n)
Space:O(1)
Asked at
GoogleAmazonMicrosoft