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     }

  • 相关阅读:
    hadoop之 hadoop日志存放路径
    grpc的数据包监控
    HTTP2 概述
    gRPC的简单Go例子
    win下环境变量的设置
    Go的pprof使用
    graphviz
    学习Golang的步骤建议
    golang 的 sync.WaitGroup
    【转】golang的channel的几种用法
  • 原文地址:https://www.cnblogs.com/springfor/p/3877059.html
Copyright © 2011-2022 走看看