Iterate in reverse order Java O(n) solution


  • 0
    N
    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices.length==0) {
                return 0;
            }
            int n = prices.length;
            int profit = 0, maxSoFar=-1, maxProfit=0;
            
            for(int i=n-1; i>=0; i--) {
                if(prices[i]>maxSoFar) {
                    maxSoFar = prices[i];
                }
                profit = maxSoFar - prices[i];
                maxProfit = profit>maxProfit ? profit : maxProfit;
            }
            return maxProfit;
        }
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.