What is the best strategy to buy and sell stock for maximum profit?

DSA
Easy
77K views

This classic problem involves finding the maximum profit from a single transaction given daily stock prices. It evaluates your ability to track minimums and maximize gains in a single pass.

Why Interviewers Ask This

This question is fundamental for assessing algorithmic thinking and optimization skills. Interviewers look for candidates who can identify the pattern of buying low and selling high without looking ahead. It tests the ability to maintain state variables like minimum price and maximum profit while traversing data. The simplicity of the problem often hides the need for precise logic to avoid off-by-one errors.

How to Answer This Question

Begin by defining the goal: maximize the difference between a future selling price and a past buying price. Propose a single-pass algorithm where you track the lowest price seen so far. Update the maximum profit at each step by comparing the current price minus the minimum price. Explain why you cannot sell before buying and how the algorithm naturally enforces this constraint.

Key Points to Cover

  • Track minimum price dynamically
  • Calculate profit at every step
  • Single pass traversal
  • O(n) time complexity

Sample Answer

The optimal approach is to traverse the price array once while maintaining the minimum price encountered so far. At each step, I calculate the potential profit by subtracting the minimum price from the current price. If this profit is greater than the recorded maximum profit, I update the maximum. This ensures we always buy at the lowest point before the current day, achieving O(n) time complexity with O(1) space.

Common Mistakes to Avoid

  • Trying to sort the array
  • Comparing all pairs of days
  • Ignoring the order of transactions

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 49 DSA questions