zoukankan      html  css  js  c++  java
  • 0121. Best Time to Buy and Sell Stock (E)

    Best Time to Buy and Sell Stock (E)

    题目

    Say you have an array for which the (i^{th}) element is the price of a given stock on day i.

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

    Note that you cannot sell a stock before you buy one.

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 5
    Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
                 Not 7-1 = 6, as selling price needs to be larger than buying price.
    

    Example 2:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.
    

    题意

    找到数组中两个数的最大差,注意较小数需要排在较大数之前。

    思路

    使用类似动态规划的方法:从左向右遍历数组,记录leftMin为以当前下标为右边界的左子数组中的最小值,每次判断更新leftMin,并判断当前值减去leftMin是否大于最大利润,是则更新最大利润。与动态规划的区别在于不需要另开数组记录每一个下标对应的leftMin。


    代码实现

    Java

    class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0) {
                return 0;
            }
    
            int leftMin = prices[0];
            int maxProfit = 0;
            for (int i = 1; i < prices.length; i++) {
                if (prices[i] < leftMin) {
                    leftMin = prices[i];
                } else if (prices[i] - leftMin > maxProfit) {
                    maxProfit = prices[i] - leftMin;
                }
            }
            return maxProfit;
        }
    }
    

    JavaScript

    /**
     * @param {number[]} prices
     * @return {number}
     */
    var maxProfit = function (prices) {
      let leftMin = prices[0]
      let maxProfit = 0
      for (let i = 1; i < prices.length; i++) {
        maxProfit = Math.max(maxProfit, prices[i] - leftMin)
        leftMin = Math.min(leftMin, prices[i])
      }
      return maxProfit
    }
    
  • 相关阅读:
    docker--docker介绍
    docker--虚拟化
    高级运维工程师的打怪升级之路
    mysql常用函数
    CentOS 7 下使用 Firewall
    51nod 1094 和为k的连续区间(map+前缀和)
    51nod 1092 回文字符串(dp)
    51nod 1062 序列中最大的数(打表预处理)
    51nod 1284 2 3 5 7的倍数(容斥原理+反面思考)
    51nod 1347 旋转字符串(思维好题)
  • 原文地址:https://www.cnblogs.com/mapoos/p/13692233.html
Copyright © 2011-2022 走看看