zoukankan      html  css  js  c++  java
  • 剑指 Offer 63. 股票的最大利润

    剑指 Offer 63. 股票的最大利润

    地址:剑指 Offer 63. 股票的最大利润

    假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

    示例 1:

    输入: [7,1,5,3,6,4]
    输出: 5
    解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
    注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
    示例 2:

    输入: [7,6,4,3,1]
    输出: 0
    解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

    限制:

    0 <= 数组长度 <= 10^5

    
    
    import (
        _ "fmt"
        "math"
    )
    
    func maxProfit(prices []int) int {
        maxProfit, minPrice := 0, math.MaxInt32
        for _, price := range prices {
            minPrice = min(price, minPrice)
            maxProfit = max(maxProfit, price - minPrice)
            //fmt.Printf("price: %d, minPrice: %d, maxProfit: %d
    ", price, minPrice, maxProfit)
        }
        return maxProfit
    }
    
    func max(a, b int) int {
        if a >= b {
            return a
        } else {
            return b
        }
    }
    
    func min(a, b int) int {
        if a <= b {
            return a
        } else {
            return b
        }
    }
    
  • 相关阅读:
    实现系统托盘
    MDI窗体应用
    C#窗体的常用设置
    什么是UWP应用
    关于用js写缓动 动画
    关于tab栏切换的解析
    函数
    for循环
    if语句
    js
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/14342713.html
Copyright © 2011-2022 走看看