Best Time to Buy and Sell Stock II
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ prices.length ≤ 12 - ◆
0 ≤ prices[i] ≤ 1000
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteWalk the days one at a time, and at every day ask what state you're in: are you currently holding a share or not? From either state there are two live choices — do nothing and move on, or act (buy if you're empty-handed, sell if you're holding) and move on. Trying both choices at every single day and keeping the better outcome is correct, but the same (day, holding) situation gets rediscovered through many different sequences of past choices, so the work roughly doubles with every extra day.
O(2ⁿ)O(n)1class Solution {
2 private int[] prices;
3
4 public int maxProfit(int[] prices) {
5 this.prices = prices;
6 return solve(0, false);
7 }
8
9 private int solve(int day, boolean holding) {
10 if (day == prices.length) return 0;
11 int doNothing = solve(day + 1, holding);
12 int act;
13 if (holding) {
14 act = prices[day] + solve(day + 1, false);
15 } else {
16 act = -prices[day] + solve(day + 1, true);
17 }
18 return Math.max(doNothing, act);
19 }
20}Optimal — Greedy Sum of Every Rising Step
OptimalSince there's no limit on how many round trips you can make and no cost per trade, the biggest possible total gain is just the sum of every single day-to-day rise in the price. Any upward run can always be captured by "buying" right before it starts and "selling" right after it ends — and a longer run's total gain equals the sum of its individual daily rises anyway, so there's never a reason to treat a multi-day climb as one trade instead of several back-to-back ones. A single pass comparing each day to the one before it is enough.
O(n)O(1)1class Solution {
2 public int maxProfit(int[] prices) {
3 int profit = 0;
4 for (int i = 1; i < prices.length; i++) {
5 if (prices[i] > prices[i - 1]) {
6 profit += prices[i] - prices[i - 1];
7 }
8 }
9 return profit;
10 }
11}