Starter

Best Time to Buy and Sell Stock

Problem
LC 121
Difficulty
Easy
Pattern
Greedy
File
leetcode4BestTimeToBuySellStock.java
Path
pkg5leetcode/leetcode4BestTimeToBuySellStock.java
Package
pkg5leetcode
Command
java pkg5leetcode/leetcode4BestTimeToBuySellStock.java

One buy + one sell. Maximize profit (sell after buy).

Approach
track the minimum price so far; best profit = price - minSoFar.
Complexity
Time O(n), Space O(1).

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/leetcode4BestTimeToBuySellStock.java
1package pkg5leetcode;2 3/*4 * LeetCode 121: Best Time to Buy and Sell Stock  (Easy)5 * -----------------------------------------------------6 * One buy + one sell. Maximize profit (sell after buy).7 *8 * APPROACH: track the minimum price so far; best profit = price - minSoFar.9 * COMPLEXITY: Time O(n), Space O(1).10 */11public class leetcode4BestTimeToBuySellStock {12 13    static int maxProfit(int[] prices) {14        int minPrice = Integer.MAX_VALUE, best = 0;15        for (int p : prices) {16            minPrice = Math.min(minPrice, p);17            best = Math.max(best, p - minPrice);18        }19        return best;20    }21 22    public static void main(String[] args) {23        check(maxProfit(new int[]{7, 1, 5, 3, 6, 4}) == 5, "buy@1 sell@6");24        check(maxProfit(new int[]{7, 6, 4, 3, 1}) == 0, "decreasing -> 0");25        check(maxProfit(new int[]{1, 2}) == 1, "simple");26        System.out.println("leetcode4BestTimeToBuySellStock: all tests passed");27    }28 29    static void check(boolean cond, String name) {30        if (!cond) throw new AssertionError("FAILED: " + name);31        System.out.println("  PASS " + name);32    }33}