DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #122. Best Time to Buy and Sell Stock II

Linear Time and Constant Space.

Time Complexity: O(n)

Single loop through the array from index 1 to n-1
Each iteration does constant time operations (comparison, subtraction, addition)
Visit each element exactly once = O(n)

Space Complexity: O(1)

Only uses a constant amount of extra variables (profit, i)
No additional data structures that grow with input size
Space usage remains the same regardless of array size

class Solution {
    public int maxProfit(int[] prices) {

        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
           if (prices[i] > prices[i-1]) {
           profit += prices[i] - prices[i-1];
        }
    }
    return profit;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)