algorithm icon indicating copy to clipboard operation
algorithm copied to clipboard

剑指Offer_63_MaxProfit

Open dayAndnight2018 opened this issue 6 years ago • 0 comments

`for (int i = 2; i < prices.length; i++) { int curDiff = prices[i] - minPrice;

        if (curDiff > maxDiff) {
            maxDiff = curDiff;
        }

        if (prices[i] < minPrice) {
            minPrice = prices[i];
        }
    }`

此处更新最低价格的时机不太对,如果在计算结束计算价格的话,会忽略 i = 1位置价格最低的情况。

样例: {9,1,8,5,7,12,11,9} 输出是7 正确输出11

建议:

`public int calc(int[] array){ if (array == null || array.length < 2) { return -1; }

    int min = array[0];
    int profit = array[1] - array[0];
    for(int i = 2; i < array.length; i++){
        if(array[i-1]<min){
            min = array[i-1];
        }
        if(array[i] - min > profit){
            profit = array[i] - min;
        }
    }
    
    return profit;
}`

dayAndnight2018 avatar Jul 24 '19 03:07 dayAndnight2018