My clean Java solution with comments


  • 4
    W
    public int maxProfit(int[] A) {
        if(A == null || A.length == 0)
            return 0;
        int max = 0;    //最大利润
        int curMin = A[0];//当前已知的最小价格
        for(int price : A) {
            curMin = Math.min(curMin, price);   //更新最小价格
            max = Math.max(max, price-curMin);  //最大利润=当前价格-已知的最小价格
        }
        return max;
    }

Log in to reply
 

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