Maximizing Stock Trading Profits Through Incremental Gains
Given an integer array prices where prices[i] represents the stock price on day i, determine the maximum profit achievable. You may engage in multiple transactions (buy one and/or sell one share of the stock each day) but can hold at most one share at any time. Buying and selling on the same day is permitted. Return the maximum possible profit.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No profitable transaction is possible.
Greedy Approach
This method accumulattes profit from every consecutive price increase.
class StockProfit {
public int calculateProfit(int[] priceData) {
int totalGain = 0;
for (int i = 1; i < priceData.length; i++) {
if (priceData[i] > priceData[i - 1]) {
totalGain += priceData[i] - priceData[i - 1];
}
}
return totalGain;
}
}
Peak-Valley Scenning
An alternative method tracks local minima and maxima.
class TradingStrategy {
public int maxProfit(int[] dailyPrices) {
int peak = dailyPrices[0];
int valley = dailyPrices[0];
int idx = 0;
int totalProfit = 0;
int n = dailyPrices.length;
while (idx < n - 1) {
while (idx < n - 1 && dailyPrices[idx] >= dailyPrices[idx + 1]) idx++;
valley = dailyPrices[idx];
while (idx < n - 1 && dailyPrices[idx] <= dailyPrices[idx + 1]) idx++;
peak = dailyPrices[idx];
totalProfit += peak - valley;
}
return totalProfit;
}
}