zoukankan      html  css  js  c++  java
  • 2020-10-30:给定一个正数数组arr(即数组元素全是正数),找出该数组中,两个元素相减的最大值,其中被减数的下标不小于减数的下标。即求出: maxValue = max{arr[j]-arr[i] and j >= i}?

    福哥答案2020-10-30:
    1.双重遍历法。
    2.一次遍历法。
    golang代码如下:

    package main
    
    import "fmt"
    
    const INT_MAX = int(^uint(0) >> 1)
    
    func main() {
        s := []int{7, 1, 5, 3, 6, 4}
        fmt.Println("双重遍历法:", MaxProfit2(s))
        fmt.Println("一次遍历法:", MaxProfit1(s))
    }
    
    //双重遍历法
    func MaxProfit2(prices []int) int {
        maxprofit := 0
        for i := 0; i < len(prices); i++ {
            for j := i + 1; j < len(prices); j++ {
                profit := prices[j] - prices[i]
                if profit > maxprofit {
                    maxprofit = profit
                }
            }
        }
        return maxprofit
    }
    
    //一次遍历法
    func MaxProfit1(prices []int) int {
        minprice := INT_MAX
        maxprofit := 0
        for i := 0; i < len(prices); i++ {
            if prices[i] < minprice {
                minprice = prices[i]
            } else if prices[i]-minprice > maxprofit {
                maxprofit = prices[i] - minprice
            }
        }
        return maxprofit
    }
    

      执行结果如下:

  • 相关阅读:
    HTML DOM 06 节点关系
    HTML DOM 05 事件(三)
    HTML DOM 05 事件(二)
    HTML DOM 05 事件(一)
    html DOM 04 样式
    html DOM 03 节点的属性
    html DOM 02 获取节点
    html DOM 01 节点概念
    JavaScript 29 计时器
    JavaScript 28 弹出框
  • 原文地址:https://www.cnblogs.com/waitmoon/p/13904413.html
Copyright © 2011-2022 走看看