1. Problem Statement
You are given an array prices[]
where prices[i]
is the stock price on the i-th
day.
You may:
- Buy and/or sell the stock any number of times.
- You can buy and sell on the same day.
- You cannot hold more than one share at a time.
Goal: Return the maximum profit you can make.
Example:
Input: prices = [7,1,5,3,6,4] Output: 7
Explanation:
- Buy on day 1 (price = 1), sell on day 2 (price = 5) → profit = 4
- Buy on day 3 (price = 3), sell on day 4 (price = 6) → profit = 3
- Total profit = 4 + 3 = 7
2. Solution approach
Let’s look at this example:
prices = [7, 1, 5, 3, 6, 4]
We represent each day and compare it with the previous one:
Day: 0 1 2 3 4 5 Price: 7 1 5 3 6 4 Change: ↓ ↑ ↓ ↑ ↓ (↓) (profit) (↓) (profit)
Profit Calculation:
- Day 1: Price = 1 (lower than 7) → No profit
- Day 2: Price = 5 (higher than 1) → Buy at 1, Sell at 5 → Profit = 4
- Day 3: Price = 3 (lower than 5) → No profit
- Day 4: Price = 6 (higher than 3) → Buy at 3, Sell at 6 → Profit = 3
- Day 5: Price = 4 (lower than 6) → No profit
Total Profit = 4 + 3 = 7
3. Approach in Simple Words
- Start from day 1 and move through the array.
- If today’s price is more than yesterday’s, we assume:
- We bought the stock yesterday
- Sold it today
- Add the profit to our total
- Do this for every upward price move.
Let’s simulate it step by step:
prices = [7, 1, 5, 3, 6, 4] profit = 0 Day 1: 1 < 7 → no action Day 2: 5 > 1 → profit += 5 - 1 = 4 Day 3: 3 < 5 → no action Day 4: 6 > 3 → profit += 6 - 3 = 3 Day 5: 4 < 6 → no action Total profit = 4 + 3 = 7
4. Java implementation
public class StockProfitCalculator { public int maxProfit(int[] prices) { int profit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { profit += prices[i] - prices[i - 1]; } } return profit; } }