zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock leetcode java

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    题解:

    这道题只让做一次transaction,那么就需要找到价格最低的时候买,价格最高的时候卖(买价的日期早于卖价的日期)。从而转化为在最便宜的时候买入,卖价与买价最高的卖出价最大时,就是我们要得到的结果。

    因为我们需要买价日期早于卖价日期,所以不用担心后面有一天价格特别低,而之前有一天价格特别高而错过了(这样操作是错误的)。

    所以,只许一次遍历数组,维护一个最小买价,和一个最大利润(保证了买在卖前面)即可。

    代码如下:

    1     public int maxProfit(int[] prices) {
    2         int min = Integer.MAX_VALUE,max=0;
    3         for(int i=0;i<prices.length;i++){
    4             
    5             min=Math.min(min,prices[i]);
    6             max=Math.max(max,prices[i]-min);
    7         }
    8         return max;
    9     }

  • 相关阅读:
    宁波工程学院2020新生校赛C
    宁波工程学院2020新生校赛B
    宁波工程学院2020新生校赛A -恭喜小梁成为了宝可梦训练家~(水题)
    POJ 1611
    牛客算法周周练11E
    牛客算法周周练11C
    牛客算法周周练11A
    CodeForces 1176C
    CodeForces 445B
    UVALive 3027
  • 原文地址:https://www.cnblogs.com/springfor/p/3877059.html
Copyright © 2011-2022 走看看