EASY NC#15 Blind #2 Sliding Window
121. Best Time to Buy and Sell Stock
๐ Problem
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.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขString/array indexing
- โขSet/Map frequency counting
- โขPointer movement invariants
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Sliding Window reasoning pattern
๐ก Approach
- โ Track minimum price seen so far
- โ Calculate profit if sold today (current price - min price)
- โ Track maximum profit
- โ Time: O(n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขTrack minimum price seen so far
- โขCalculate profit if sold today (current price - min price)
- โขTrack maximum profit
Common Pitfalls
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 5
Test Case 1
Not run Input:
maxProfit([7, 1, 5, 3, 6, 4]); Expected:
5 Test Case 2
Not run Input:
maxProfit([7, 6, 4, 3, 1]); Expected:
0 Test Case 3
Not run Input:
maxProfit([1]); Expected:
0 ๐ Code Editor
๐ค Output