📑 题目:121. 买卖股票的最佳时机

🚀 本题 LeetCode 传送门

题目大意

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。

解题思路

  • 题目要求找出股票中能赚的钱最多的差价
  • 这一题也有多个解法,可以用 DP,也可以用单调栈

代码

  1. package leetcode
  2. // 解法一 模拟 DP
  3. func maxProfit(prices []int) int {
  4. if len(prices) < 1 {
  5. return 0
  6. }
  7. min, maxProfit := prices[0], 0
  8. for i := 1; i < len(prices); i++ {
  9. if prices[i]-min > maxProfit {
  10. maxProfit = prices[i] - min
  11. }
  12. if prices[i] < min {
  13. min = prices[i]
  14. }
  15. }
  16. return maxProfit
  17. }
  18. // 解法二 单调栈
  19. func maxProfit1(prices []int) int {
  20. if len(prices) == 0 {
  21. return 0
  22. }
  23. stack, res := []int{prices[0]}, 0
  24. for i := 1; i < len(prices); i++ {
  25. if prices[i] > stack[len(stack)-1] {
  26. stack = append(stack, prices[i])
  27. } else {
  28. index := len(stack) - 1
  29. for ; index >= 0; index-- {
  30. if stack[index] < prices[i] {
  31. break
  32. }
  33. }
  34. stack = stack[:index+1]
  35. stack = append(stack, prices[i])
  36. }
  37. res = max(res, stack[len(stack)-1]-stack[0])
  38. }
  39. return res
  40. }