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
    }
    

      执行结果如下:

  • 相关阅读:
    第8章 字符串
    第7章 方法
    第6章 类和对象
    第5章 数组
    第4章 循环结构、break与continue
    第3章 选择结构
    第2章 变量、数据类型和运算符
    Codeforces Round #426 (Div. 2)
    CCNA学前基础一
    Tinkoff Challenge
  • 原文地址:https://www.cnblogs.com/waitmoon/p/13904413.html
Copyright © 2011-2022 走看看