Java O(1) solution ~ 90%


  • 0
    K
    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0;
            int sp = 0; //sell price
            for(int i = prices.length-1; i>=0; i--){ //read array from right to left, 
                if(prices[i]>sp){
                    sp = prices[i]; // identify possible selling price
                }else{
                    if((sp - prices[i]) > max){
                        max = sp- prices[i]; //calculate and assign max profit
                    }
                }    
            }
            return max;
        }
    }
    

  • 0
    N

    This is an O(n) solution


Log in to reply
 

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