Leetcode Q122 (Medium): Best time to buy and sell stocks

Problem statements:




Problem Analysis:

Edge Cases:


Solutions:

Brute-Force Approach (Recursion with Backtracking):



Optimized Approach (Greedy Algorithm)

Implemention - Java:

    /**
     * Calculates the maximum profit by buying and selling a stock multiple times.
     * This method uses a greedy approach to sum all positive price differences.
     * @param prices An array of stock prices.
     * @return The maximum possible profit.
     */
    public int maxProfit(int[] prices) {
        // Handle edge cases where no transaction is possible
        if (prices == null || prices.length < 2) {
            return 0;
        }

        int maxProfit = 0;
        // Iterate through the prices and add up all increments
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i-1]) {
                maxProfit += prices[i] - prices[i-1];
            }
        }
        return maxProfit;
    }


------ End ------