DDSA Solutions

Stock Buy and Sell – Multiple Transaction Allowed

Time: O(n)
Space: O(1)

Problem Overview

Maximum profit with unlimited transactions.

See our study guide for structured GFG and LeetCode practice.

Intuition

Maximum profit with unlimited transactions. Sum all positive differences.

Algorithm

  1. 1For each day: if prices[i] > prices[i-1]: profit += prices[i] - prices[i-1].

Common Pitfalls

  • Same as LC 122. Greedy: capture every upward move. O(n) O(1).
Stock Buy and Sell – Multiple Transaction Allowed.java
Java
// Approach: Greedy. Sum all positive consecutive differences (buy every valley, sell every peak).
// Time: O(n) Space: O(1)
class Solution {
    public int maximumProfit(int prices[]) {
        int res = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                int diff = prices[i] - prices[i - 1];
                res += diff;
            }
        }
        return res;
    }
}
Was this solution helpful?