Skip to content

剑指Offer_63_MaxProfit #1

Description

@dayAndnight2018

`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;
}`

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions