Solvarch
DSA ProblemsProgressPlanRoadmapsReviewCheat SheetsCompaniesSystem DesignCS FundamentalsQuestion Bank
Theme
Problems

Best Time to Buy and Sell Stock

Easy
arraydynamic-programminggreedy

You are given an array prices where prices[i] is the price of a stock on day i. Buy on one day and sell on a later day to maximize profit. Return the maximum profit, or 0 if no profit is possible.

Input: one line of space-separated integers prices. Output: the maximum profit.

Example 1
Input:
7 1 5 3 6 4
Output:
5

Buy at 1, sell at 6 → profit 5.

Example 2
Input:
7 6 4 3 1
Output:
0

Prices only fall; no profitable trade.

Constraints

  • 1 ≤ prices.length ≤ 10^5
  • 0 ≤ prices[i] ≤ 10^4
Watch a video walkthrough

Run your code against the sample tests, or Submit to run the full suite.