Time - O(n) & Space - O(1) Beats 88% Java Solution


  • 0
    D
    public class Solution {
        public int maxProfit(int[] prices) {
            int n = prices.length;
            if (n <=1) {
                return 0;
            }
            int min = prices[0];
            int maxProfit = 0;
            for(int i=0;i<n;i++) {
                if(prices[i] < min) {
                    min = prices[i];
                }
                
                if(prices[i] - min > maxProfit) {
                    maxProfit = prices[i] -min;
                }
            }
            return maxProfit;
            
        }
    }
    

Log in to reply
 

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