NOTE

买卖股票的最佳时机

买卖股票的最佳时机 的 LeetCode 解题笔记。

Data Structures & Algorithms创建于 更新于 约 1 分钟读完historical

这是历史学习笔记,可能存在过时或不完整的理解。

1. 题目描述

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

2. 思路

  1. 思路一
    • 暴力法
    • 确定一个买入,遍历后面的卖出找出差值最大的
  2. 思路二
    • 利润最大=max卖出-min买入
    • 那么遍历过程中记录min买入,卖出则是一个个减即可

3. 实现

3.1. 暴力法

func maxProfit(prices []int) int {
	if len(prices) == 0 {
		return 0
	}

	max := 0
	for i := 0; i < len(prices)-1; i++ {
		buy := prices[i]
		for j := i + 1; j < len(prices); j++ {
			sell := prices[j]
			max = Max(max, sell-buy)
		}
	}

	return max
}

func Max(data ...int) int {
	max := data[0]
	for i := 1; i < len(data); i++ {
		if data[i] > max {
			max = data[i]
		}
	}
	return max
}

3.2. 最小值

func maxProfit(prices []int) int {
    minPrice := math.MaxInt32
    maxProfit := 0
    for _, price := range prices {
        minPrice = min(minPrice, price)
        maxProfit = max(maxProfit, price- minPrice)
    }
    return maxProfit
}

func min(a, b int) int {
    if a < b {
        return a
    }
    return b
}

func max(a, b int) int {
    if a < b {
        return b
    }
    return a
}

4. 参考

讨论

使用 GitHub 账号参与讨论,评论会保存在 GitHub Issues 中。在 GitHub 查看