๐ Best Time to Buy and Sell Stock โ (LeetCode #121)
In this post, Iโll walk through one of the most popular array-based problems on LeetCode โ Best Time to Buy and Sell Stock โ and how the Sliding Window pattern gives us a clean and efficient solution.
๐ง Problem
You're given an array prices where prices[i] is the price of a given stock on the i-th day.
You want to maximize your profit by choosing a single day to buy one stock and a different day in the future to sell that stock.
Return the maximum profit you can achieve. If you canโt achieve any profit, return 0.
๐งฎ Example:
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
# Buy on day 1 (price = 1), sell on day 4 (price = 6), profit = 6 - 1 = 5
Python Code:
def maxProfit(prices):
min_price = float('inf') # Start with the highest possible value
max_profit = 0 # No profit yet
for price in prices:
# If we find a lower price, update min_price
if price < min_price:
min_price = price
else:
# Calculate profit and update max_profit if itโs higher
profit = price - min_price
max_profit = max(max_profit, profit)
return max_profit
Approach 2 :Using two pointers
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# Using the approach of two pointers
l,r=0,1#Left=>Buy and Right=>sell
maxProfit=0
while r<len(prices):
if prices[l]<prices[r]:
#Buy low and sell hight=Profit
profit=prices[r]-prices[l]
maxProfit=max(maxProfit,profit)
else:
l=r
r+=1
return maxProfit
๐ Explanation
We use two pointers:
l to track the buy day
r to track the sell day
If prices[r] > prices[l], we calculate profit and update the maximum.
If prices[r] <= prices[l], we found a lower buy price โ move the left pointer to r.
โฑ Time Complexity:
O(n) โ Single pass through the array.
๐ง Space Complexity:
O(1) โ No extra space needed.
Image Visualization:
Maximum Subarray:
Leetcode(53)
๐ Problem Statement
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum, and return its sum.
๐งช Example
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6
Intuition
At every index, we decide:
Should we start a new subarray?
Or should we extend the current one?
We only keep extending when it gives us a better sum.
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxsub=nums[0]
curr_sub=0
for n in nums:
if curr_sub<0:
#ie Negative
curr_sub=0
curr_sub+=n
maxsub=max(maxsub,curr_sub)
return maxsub
โ๏ธ What I Learned
This problem taught me:
How to reduce a brute force O(n^2) solution to O(n)
The importance of tracking state efficiently
That writing blogs helps lock in these concepts ๐
๐ Related Problems
Maximum Product Subarray
Contiguous Array (binary nums)
House Robber
Top comments (0)