golang_算法:leetcode_动态规划02-买卖股票的最佳时机

package main

import (
	"fmt"
	"math"
)

//一次遍历
func maxProfit(prices []int) int {
	minNum := math.MaxInt32
	maxPro := 0
	for _, value := range prices {
		if value < minNum {
			minNum = value
		}
		if value - minNum > maxPro {
			maxPro = value - minNum
		}
	}
	return maxPro
}

//暴力穷举法
func maxProfit2(prices []int) int {
	l := len(prices)
	maxpro := 0
	for i := 0; i < l-1; i++ {
		for j := i+1; j < l; j++ {
			sub := prices[j] - prices[i]
			if sub > maxpro {
				maxpro = sub
			}
		}
	}
	return maxpro
}

func main() {
	nums := []int{7,1,5,3,2,6}
	fmt.Println(maxProfit2(nums))
}

你可能感兴趣的:(algorithm)