zoukankan      html  css  js  c++  java
  • 买卖股票专题系列1---买卖股票的最佳时机1

    题目:

      给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

    题解:

      由于只能买卖一次股票,所以针对每天的价格要找到之前股票价格的最小值,这样才使得利润最大。即对于prices[]数组中的每个值,要找到这个值左边的最小值。下面直接上代码:

    Java版本:

     public int maxProfit(int[] prices) {
            //没有买入股票或者在第一天买入了股票
            if(prices == null || prices.length <= 1) return 0;
            //每次交易都找到左边的最小值,这样每次利润才最大,然后比较选取每次利润的最大值
            int max = 0 ,minPrices = prices[0];
            for(int i=1;i < prices.length;i++){
                minPrices = Math.min(minPrices,prices[i-1]);
                if(minPrices < prices[i]){
                    max = Math.max(prices[i] - minPrices, max);
                }
            }
            return max;
        }
    JS版本:
    var maxProfit = function(prices) {
      //每次交易都找到左边的最小值,这样每次利润才最大,然后比较选取每次利润的最大值
      if(prices == null || prices.length <= 1) return 0;
      let max = 0;
      let minprices = prices[0];
      for(let i = 1;i<prices.length;i++){
        minprices = Math.min(minprices,prices[i]);
        max = Math.max(max,prices[i] - minprices);
      }
      return max;
    };
  • 相关阅读:
    Winform dataGridView 用法
    C# 网络地址下载
    C# 位数不足补零
    python中随机生成整数
    python中time模块的调用及使用
    Windows server 2016 2019远程端口修改操作
    linux查看所有用户的定时任务 crontab
    使用Docker基于Nexus3快速搭建Maven私有仓库
    Phoenix docker 测试
    mysql锁表处理
  • 原文地址:https://www.cnblogs.com/bobobjh/p/14414565.html
Copyright © 2011-2022 走看看