# 股票的最大利润|买入时机(稍微有些变种) --- 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?最佳买入点?最佳卖出点? ## 题目描述: ```javascript= 示例 1: 输入: [7,1,5,3,6,4] 输出: [5,2,5] 解释: 第2天(股票价格 = 1)的时候买入 第5天(股票价格=6)的时候卖出 最大利润 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 示例 2: 输入: [7,6,4,3,1] 输出: [0,0,0] 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 限制:0 <= 数组长度 <= 10^5 ``` ## 代码实现 ```go package main import ( "fmt" ) func main() { fmt.Println(maxProfit([]int{7,1,5,3,6,4})) fmt.Println(maxProfit([]int{1,2,3,4,5,9})) fmt.Println(maxProfit([]int{7,6,5,3,2,8})) fmt.Println(maxProfit([]int{7,6,5,3,2,1})) } func maxProfit(costs []int) []int { tmp, start, end, profit := 0, -1, -1, 0 if len(costs) < 2 { return []int{0, 0, 0} } for i := range costs { if costs[tmp] > costs[i] { tmp = i } else if profit < costs[i] - costs[tmp]{ profit = costs[i] - costs[tmp] start = tmp end = i } } return []int{profit, start + 1, end + 1} } ``` ## 结果输出 ```shell= [5 2 5] [8 1 6] [6 5 6] [0 0 0] ``` ###### tags: LeeCode 金融 富途 股票 来源:力扣(LeetCode) 链接: 剑指 Offer 63.股票的最大利润 https://leetcode.cn/problems/gu-piao-de-zui-da-li-run-lcof 剑指 Offer 121.买卖股票的最佳时机 https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/