Easy Java solution. O(n) time and O(1) space complexity.


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

Log in to reply
 

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