Best Time to Buy and Sell Stock

Read the lesson → understand the pattern → then code. Tutor works offline (built-in teacher); optional Cursor/Gemini keys upgrade chat quality.

Topic refresher: Arrays — Index Thinking

Treat every array problem as: What do I know at index i? What must I remember from the past?

// Running best pattern
int best = nums[0];
for (int i = 1; i < n; i++) {
    // update state using nums[i]
    best = max(best, candidate);
}
return best;
Arrays

Best Time to Buy and Sell Stock

Easy
LeetCode
3/14
EasyArraysLeetCode #121

Buy Low, Sell High (one transaction)

Track the minimum price so far. At each day, profit = price - minSoFar. Keep max profit.

One pass. No nested loops.

Examples

Example 1

Input

6
7 1 5 3 6 4

Output

5
Example 2

Input

5
7 6 4 3 1

Output

0

Stuck? Take a nudge

C++17