Java Solution with O(n) time and O(1) space


  • 0
    N
    public class Solution {
        public int maxProfit(int[] prices) {
            if(prices == null || prices.length ==0 || prices.length ==1) return 0;
            int profit = 0;
            int i = 0;
            
            for(;i<prices.length-1;i++){
                if(prices[i]<prices[i+1]){
                    profit -= prices[i];
                    break;
                }
            }
            if(i == prices.length-1) return 0;
            
            while(true){
                if(i == prices.length-1){
                    profit += prices[i];
                    break;
                }
                if(prices[i]>prices[i+1]){
                    profit+=prices[i];
                    profit-=prices[i+1];
                }
                i++;
                    
            }
           
            return profit;
        }
    }

Log in to reply
 

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