Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Maximizing Stock Trading Profits Through Incremental Gains

Tech May 13 3

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;
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.