Best Time to Buy and Sell Stock (Greedy Scans) Problem
Best Time to Buy and Sell Stock (Greedy Scans) Problem — ExecCode Easy DSA Practice
Solve the Best Time to Buy and Sell Stock (Greedy Scans) problem on ExecCode. Free online easy DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.
Problem description
Given daily stock prices, choose one buy day before one sell day to maximize profit. Read the array once while treating the best earlier buy price as the left side of a moving window and the current day as the right side. If selling today is profitable, update the answer; if today is cheaper than every earlier day, move the buy candidate to today.
Examples
Input prices = [7, 1, 5, 3, 6, 4]; Output 5. Input prices = [7, 6, 4, 3, 1]; Output 0. Input prices = [2, 4, 1, 7]; Output 6
Constraints
1 ≤ prices.length ≤ 10⁵ 0 ≤ prices[i] ≤ 10⁴
Practice Best Time to Buy and Sell Stock (Greedy Scans) free on ExecCode. Browse DSA problems, topic map, and placement guides.