Bird
Raised Fist0
Interview Prepdp-linear-fibonaccieasyAmazonFacebookGoogleBloomberg

Best Time to Buy and Sell Stock (1 tx)

Choose your preparation mode4 modes available
📋
Problem

Imagine you are an investor who wants to maximize profit by buying and selling a single stock once over a period of days. You want to know the best day to buy and the best day to sell to maximize your gain.

Given an array prices where prices[i] is the price of a given stock on the ith day, find the maximum profit you can achieve by making at most one transaction (i.e., buy one and sell one share of the stock). If no profit can be made, return 0.

1 ≤ prices.length ≤ 10^50 ≤ prices[i] ≤ 10^4
Edge cases: Only one day → output 0 (cannot sell)Prices are all the same → output 0 (no profit)Prices strictly decreasing → output 0 (no profit)
</>
IDE
def maxProfit(prices: list[int]) -> int:public int maxProfit(int[] prices)int maxProfit(vector<int> &prices)function maxProfit(prices)
def maxProfit(prices):
    # Write your solution here
    pass
class Solution {
    public int maxProfit(int[] prices) {
        // Write your solution here
        return 0;
    }
}
#include <vector>
using namespace std;

int maxProfit(vector<int> &prices) {
    // Write your solution here
    return 0;
}
function maxProfit(prices) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: 0Always returning 0 without checking for profitable transactions.✅ Track min_price and update max_profit = max(max_profit, current_price - min_price) during iteration.
Wrong: profit from local max instead of global maxGreedy approach that sells at first local maximum instead of global maximum.✅ Do not sell immediately; track min_price globally and update max_profit at each step.
Wrong: positive profit on strictly decreasing pricesNot checking if current price is less than min_price before updating profit.✅ Update min_price when current price is lower; only update max_profit if current price - min_price > max_profit.
Wrong: TLE on large inputUsing O(n^2) brute force nested loops approach.✅ Implement O(n) single pass solution tracking min_price and max_profit.
✓
Test Cases
t1_01basic
Input{"prices":[7,1,5,3,6,4]}
Expected5

Buy on day 2 (price=1) and sell on day 5 (price=6), profit = 6-1 = 5.

t1_02basic
Input{"prices":[3,8,6,7,6,9,2]}
Expected6

Buy on day 1 (price=3) and sell on day 2 (price=8), profit = 8-3 = 5; better to buy on day 7 (price=2) and sell on day 6 (price=9) is invalid since sell must be after buy; best is buy day 1 sell day 6 profit 9-3=6.

t2_01edge
Input{"prices":[5]}
Expected0

Only one day, cannot sell after buying, so profit is 0.

t2_02edge
Input{"prices":[4,4,4,4,4]}
Expected0

All prices are the same, no profit possible, so output is 0.

t2_03edge
Input{"prices":[9,7,5,3,1]}
Expected0

Prices strictly decreasing, no profit possible, so output is 0.

t3_01corner
Input{"prices":[1,2,3,4,5]}
Expected4

Prices strictly increasing, best to buy on day 1 and sell on last day, profit = 5-1 = 4.

t3_02corner
Input{"prices":[3,2,6,1,4]}
Expected4

Buy on day 2 (price=2) and sell on day 3 (price=6), profit = 4; buying on day 4 (price=1) and selling on day 5 (price=4) yields profit 3, less than 4.

t3_03corner
Input{"prices":[7,1,5,3,6,4,8]}
Expected7

Buy on day 2 (price=1) and sell on day 7 (price=8), profit = 7.

t4_01performance
Input{"_description":"n=100000 at constraint boundary - executor generates this"}
⏱ Performance - must finish in 2000ms

Input size n=100000 requires O(n) solution to complete within 2 seconds.

Practice

(1/5)
1. You are given a list of daily stock prices and want to maximize profit by buying and selling stocks with the constraint that after selling a stock, you must wait one day before buying again. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Brute force recursion exploring all buy/sell/cooldown sequences without memoization
B. A greedy algorithm that buys at every local minimum and sells at every local maximum
C. Dynamic programming with state machine to track holding, cooldown, and free states
D. Divide and conquer splitting the price array into subproblems and merging results

Solution

  1. Step 1: Understand the cooldown constraint

    The cooldown day after selling prevents immediate rebuying, which breaks greedy local min/max approaches.
  2. Step 2: Recognize the need for state tracking

    Dynamic programming with states (holding, cooldown, free) models the problem accurately and efficiently.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Greedy fails on cooldown; DP state machine handles it correctly [OK]
Hint: Cooldown requires state tracking, not greedy [OK]
Common Mistakes:
  • Assuming greedy local min/max works despite cooldown
  • Ignoring cooldown day after selling
2. Examine the following code snippet for climbing stairs:
def climb_stairs(n):
    if n < 1:
        return 1
    first, second = 1, 1
    for i in range(2, n + 1):
        current = first + second
        first, second = second, current
    return second
Which line contains a subtle bug that can cause incorrect results or runtime errors?
medium
A. Line 2: Incorrect base case condition should be 'if n <= 1'
B. Line 4: Loop range should start from 1 instead of 2
C. Line 5: The addition 'first + second' should be 'first - second'
D. Line 6: The tuple assignment order is reversed

Solution

  1. Step 1: Analyze base case condition

    The condition 'if n < 1' returns 1 only when n is 0 or negative, but for n=1 it skips and runs the loop, which is incorrect.
  2. Step 2: Correct base case to 'if n <= 1'

    This ensures for n=0 or n=1, the function returns 1 immediately, matching problem definition.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Base case off-by-one causes wrong results for n=1 [OK]
Hint: Check base cases carefully for off-by-one errors [OK]
Common Mistakes:
  • Using '<' instead of '<=' in base cases
  • Incorrect loop start index
3. 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
4. What is the time complexity of the optimal bottom-up dynamic programming solution for the minimum cost climbing stairs problem, and why?
medium
A. O(n) because each step computes cost using only two previous states
B. O(n²) because each step depends on all previous steps
C. O(2^n) due to exponential recursion calls
D. O(n log n) because of sorting costs before processing

Solution

  1. Step 1: Analyze loop structure

    The bottom-up DP iterates once through the cost array of length n.
  2. Step 2: Check dependencies per iteration

    Each iteration computes current cost using only two previous values, constant time per iteration.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Single pass with O(1) work per step -> O(n) total [OK]
Hint: DP uses constant work per step, linear total time [OK]
Common Mistakes:
  • Assuming quadratic due to nested loops
  • Confusing recursion with DP iteration
  • Thinking sorting is involved
5. What is the time complexity of the optimal bottom-up DP solution for the Word Break problem, where n is the length of the input string, m is the number of unique word lengths in the dictionary, and k is the maximum word length?
medium
A. O(n * m * k) because for each position we check only word lengths and substring membership
B. O(2^n) due to exploring all segmentations recursively
C. O(n * m) because substring extraction is O(1) and membership check is O(1)
D. O(n^2) because for each index we check all previous indices

Solution

  1. Step 1: Identify loops and operations

    The outer loop runs n times. For each i, inner loop runs over m unique word lengths. Substring extraction takes O(k) time, and membership check in a set is O(1).
  2. Step 2: Combine to get total complexity

    Total time is O(n * m * k). The naive O(n^2) is incorrect because we don't check all previous indices, only those corresponding to word lengths.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Loops over n and m, substring extraction O(k) -> O(n*m*k) [OK]
Hint: Check loops and substring extraction cost carefully [OK]
Common Mistakes:
  • Assuming O(n^2) by checking all indices
  • Ignoring substring extraction cost
  • Confusing recursive exponential with DP complexity
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