Blind 75
Best Time to Buy and Sell Stock
- Problem
- LC 121
- Category
- Array
- File
- blind75_LC121BestTimeToBuyAndSellStock.java
- Path
- pkg5leetcode/blind75/blind75_LC121BestTimeToBuyAndSellStock.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC121BestTimeToBuyAndSellStock.java
- Approach
- Track min price seen; maximize profit at each day.
- Complexity
- Time O(n), Space O(1)
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Best Time to Buy and Sell Stock | LC 1215 * APPROACH: Track min price seen; maximize profit at each day.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class blind75_LC121BestTimeToBuyAndSellStock {9 static int maxProfit(int[] prices) {10 int min = Integer.MAX_VALUE, best = 0;11 for (int p : prices) {12 min = Math.min(min, p);13 best = Math.max(best, p - min);14 }15 return best;16 }17 18 public static void main(String[] args) {19 check(maxProfit(new int[]{7, 1, 5, 3, 6, 4}) == 5, "case1");20 check(maxProfit(new int[]{7, 6, 4, 3, 1}) == 0, "case2");21 System.out.println("all tests passed");22 }23 24 static void check(boolean cond, String name) {25 if (!cond) throw new AssertionError("FAILED: " + name);26 System.out.println(" PASS " + name);27 }28}