O(n) time with O(1) space simple java solution


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

    }


  • 0
    C
    This post is deleted!

  • 0
    D

    no need for
    if (prices.length == 0) {
    return 0;
    }


Log in to reply
 

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