golang_算法: leetcode_数组02-买卖股票的最佳时机 II

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/weixin_43851310/article/details/87907643
import "fmt"

//2.设计算法
//这个算法本质:当明天的价格比今天的价格贵的时候我们今天买,
// 明天卖,这样能够获取最大利润
//类似股票图,只要把所有的股市增长的全部加起来就行

func maxProfit(prices []int) int {
	var profit int
	var i int
	for i = 0; i < len(prices)-1; i++ {
		if prices[i] < prices[i+1] {
			profit += prices[i+1] - prices[i]
		}
	}
	fmt.Println(profit)
	return profit
}

func main() {
	prices := []int{1,2,3,4,5}
	maxProfit(prices)
}

Output:

4

猜你喜欢

转载自blog.csdn.net/weixin_43851310/article/details/87907643
今日推荐