122. Best Time to Buy and Sell Stock II

 Intuition

go for every possible solution


Approach

we can solve it using greedy algorithm where we calculate the profite without looking for fourther


Complexity

Time complexity: O(n)

Space complexity: O(1)

Code

class Solution {

    public int maxProfit(int[] prices) {

        int max = 0;

        int buyPrice = prices[0];

        for(int i = 0; i < prices.length; i++){

            if(prices[i] > buyPrice){

                max += prices[i] - buyPrice;

            }

            buyPrice = prices[i];

        }

        return max;

    }

}

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic 🚀 leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

14. Longest Common Prefix