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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit