Bird
Raised Fist0
Interview Prepdp-linear-fibonaccieasyAmazonFacebookGoogleBloomberg

Best Time to Buy and Sell Stock (1 tx)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize min_price and max_profit

Set min_price to the price on day 0 (7) and max_profit to 0 before starting iteration.

💡 We start with the first day's price as the minimum since we haven't seen any other prices yet.
Line:min_price = prices[0] max_profit = 0
💡 Initial values establish the baseline for comparisons in subsequent days.
📊
Best Time to Buy and Sell Stock (1 tx) - Watch the Algorithm Execute, Step by Step
Watching each update to min_price and max_profit helps you understand how the algorithm efficiently finds the best buy-sell pair without nested loops.
Step 1/10
·Active fill★Answer cell
Item 0 - wt:7 val:0
i\w012345
i=0[7,0]?????
min_price=7, max_profit=0
Item 1 - wt:1 val:0
i\w012345
i=0[7,0][1,0]????
min_price updated to 1
Item 1 - wt:1 val:0
i\w012345
i=0[7,0][1,0]????
min_price=1, max_profit=0
Item 2 - wt:5 val:4
i\w012345
i=0[7,0][1,0][1,4]???
max_profit updated to 4
Item 3 - wt:3 val:4
i\w012345
i=0[7,0][1,0][1,4][1,4]??
max_profit unchanged at 4
Item 4 - wt:6 val:5
i\w012345
i=0[7,0][1,0][1,4][1,4][1,5]?
max_profit updated to 5
Item 5 - wt:4 val:5
i\w012345
i=0[7,0][1,0][1,4][1,4][1,5][1,5]
max_profit unchanged at 5
Item 5 - wt:4 val:5
i\w012345
i=0[7,0][1,0][1,4][1,4][1,5][1,5]
Answer: max_profit=5
Initializing dp array
i\w012345
i=0[7,0][1,0][1,4][1,4][1,5][1,5]
min_price and max_profit states
Item 5 - wt:4 val:5
i\w012345
i=0[7,0][1,0][1,4][1,4][1,5][1,5]
Final max_profit = 5

Key Takeaways

✓ Tracking the minimum price seen so far allows the algorithm to find the best buy day efficiently.

Without this insight, one might try nested loops, which are less efficient and harder to visualize.

✓ The maximum profit is updated only when a better selling day is found, showing a linear progression.

This step-by-step update clarifies how the algorithm avoids unnecessary calculations.

✓ The decision to update min_price or max_profit depends on a simple comparison, illustrating a clear state machine behavior.

Seeing this decision in action helps understand the branching logic that drives the algorithm.

Practice

(1/5)
1. What is the time and space complexity of the optimal space-optimized bottom-up DP solution for the Best Time -- Cooldown problem with input size n (number of days)?
medium
A. Time: O(n), Space: O(1)
B. Time: O(2^n), Space: O(n)
C. Time: O(n), Space: O(n)
D. Time: O(n²), Space: O(n)

Solution

  1. Step 1: Identify time complexity

    The algorithm iterates once through prices array, performing constant work per iteration -> O(n) time.
  2. Step 2: Identify space complexity

    Only constant variables (hold, cool, free) are used, no arrays -> O(1) space.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single pass, constant variables -> O(n) time and O(1) space [OK]
Hint: One pass with constant states means O(n) time, O(1) space [OK]
Common Mistakes:
  • Confusing recursion stack space with iterative space
  • Assuming DP arrays used in bottom-up
2. The following code attempts to count the number of ways to decode a string. Which line contains a subtle bug that causes incorrect results for inputs containing '0'?
medium
A. if s[i] != '0':
B. curr += prev1 # inside two_digit check
C. if 10 <= two_digit <= 26:
D. prev2, prev1 = prev1, curr

Solution

  1. Step 1: Identify two-digit addition logic

    The two-digit check should add prev2, not prev1, because it represents ways two steps back.
  2. Step 2: Understand impact on '0' handling

    Adding prev1 instead of prev2 causes overcounting or invalid counts when '0' appears, e.g., '10' or '20'.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Correct two-digit addition uses prev2, not prev1 [OK]
Hint: Two-digit addition must add prev2, not prev1 [OK]
Common Mistakes:
  • Confusing prev1 and prev2 in two-digit addition
3. What is the time complexity of the top-down memoized recursive solution for the House Robber problem with input size n, and why might some candidates mistakenly think it is exponential?
medium
A. O(n^2) due to overlapping subproblems recomputed multiple times
B. O(2^n) because each call branches into two recursive calls
C. O(n) because memoization ensures each index is computed once
D. O(n log n) because recursion depth is logarithmic

Solution

  1. Step 1: Analyze recursion with memoization

    Memoization caches results for each index i, so robFrom(i) is computed once per i.
  2. Step 2: Determine total calls and complexity

    Since i ranges from 0 to n-1, total calls are O(n), each O(1) work -> O(n) time.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Without memoization, calls explode exponentially; memoization reduces to linear [OK]
Hint: Memoization reduces exponential calls to linear by caching [OK]
Common Mistakes:
  • Assuming recursion always exponential
  • Ignoring memoization effect
4. Consider the following buggy code for Jump Game II. Which line contains the subtle bug that causes incorrect results for input arrays of length 1?
medium
A. Line 2: n = len(nums)
B. Line 9: return jumps
C. Line 3: jumps = 0
D. Line 5: for i in range(n - 1):

Solution

  1. Step 1: Analyze loop range for single-element array

    When n=1, range(n-1) = range(0), so the loop does not run, and jumps remains 0.
  2. Step 2: Check if jumps=0 is correct for single-element input

    For an array of length 1, minimum jumps should be 0 (already at last index). The code returns 0, which is correct. However, if the problem expects at least one jump or code elsewhere assumes the loop runs, this can cause issues. The subtle bug is that the loop does not run for n=1, so no updates happen. If code elsewhere expects jumps increment, this is a problem.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Loop skipping for n=1 causes edge case bugs [OK]
Hint: Loop range excludes last index, skip for single-element arrays [OK]
Common Mistakes:
  • Not handling single-element arrays properly
  • Assuming loop always runs at least once
  • Returning jumps without base case check
5. What is the time complexity of the optimal greedy solution for the Jump Game problem, and why?
medium
A. O(n) because it iterates through the array once updating maxReach
B. O(n^2) because each position may check multiple jumps
C. O(n log n) due to sorting or priority queue operations
D. O(2^n) because of exploring all jump paths recursively

Solution

  1. Step 1: Identify loop structure

    The greedy solution iterates through the array once, updating maxReach in O(1) time per iteration.
  2. Step 2: Confirm no nested loops or recursion

    There are no nested loops or recursion, so total time is linear in array length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single pass over array -> O(n) time [OK]
Hint: Greedy uses single pass, no nested loops [OK]
Common Mistakes:
  • Confusing brute force with greedy complexity
  • Assuming sorting is needed
  • Forgetting recursion stack space
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard