Finding the maximum profit you can make by buying and selling stocks over a period of time is a classic coding interview problem. In this scenario, you are given an array of daily stock prices, and you want to write a program that calculates the highest profit you could accumulate by buying and selling as many times as you like.
This is solved using an approach called a Greedy Algorithm. Let's look at how this works using a fun rollercoaster analogy.
Imagine you are riding a rollercoaster where the height of the track represents the price of a stock on different days. You want to collect "climbing points" (profit) on this ride.
Since you can buy and sell as many times as you want, your strategy is simple:
- Every time the rollercoaster is going **upward** (today's price is higher than yesterday's), you capture that gain!
- Every time the rollercoaster goes **downward** (prices drop), you do nothing—you just sit back and wait for it to bottom out.
- By adding up all the upward climbs, you automatically get the maximum possible points you could ever score on the ride.
Walkthrough of the Main Method Scenario
Let's trace how the program executes step-by-step from the entry point of the main method:
The program declares two array scenarios representing stock price movements:
int arr[] = {100, 180, 260, 310, 40, 535, 695};
int arr1[] = {4, 2, 2, 2, 4};
The program calls getMaxProfit(arr) and loops through the elements starting from index 1:
- Day 1 ($180): $180 > $100 (yesterday). Yes! We add the difference:
profit += 80. Total: $80. - Day 2 ($260): $260 > $180. Yes!
profit += 80. Total: $160. - Day 3 ($310): $310 > $260. Yes!
profit += 50. Total: $210. (This matches buying at $100 and selling at $310!) - Day 4 ($40): $40 < $310. Downward slope. No profit added.
- Day 5 ($535): $535 > $40. Yes!
profit += 495. Total: $705. - Day 6 ($695): $695 > $535. Yes!
profit += 160. Total: $865. (This matches buying at $40 and selling at $695!)
The program returns the total accumulated profit: **$865**.
The program calls getMaxProfit(arr1) for the prices [4, 2, 2, 2, 4]:
- Days 1, 2, and 3: Prices drop or remain flat (
4 → 2 → 2 → 2). No profit is added. - Day 4 ($4): Price climbs: $4 > $2. Yes!
profit += 2. Total: $2.
The program returns: **$2**.
Java Implementation
Below is the complete Java code showing the profit calculation checker:
package io.practise.accolite;
public class StockBuyAndSellMaxProfitChecker {
public static void main(String[] args) {
int arr[] = {100, 180, 260, 310, 40, 535, 695};
int arr1[] = {4, 2, 2, 2, 4};
System.out.println(getMaxProfit(arr1)); // Outputs: 2
System.out.println(getMaxProfit(arr)); // Outputs: 865
}
private static int getMaxProfit(int[] arr) {
int profit = 0;
for (int i = 1; i < arr.length; ++i) {
if (arr[i] > arr[i - 1]) {
profit += arr[i] - arr[i - 1];
}
}
return profit;
}
}
Conclusion
By using a greedy approach, we don't need to predict the future or look ahead multiple days. We simply compare today's price with yesterday's price. If it is higher, we buy yesterday and sell today, accumulating all positive upward moves to guarantee the maximum profit!