当前位置: 首页 > news >正文

day 42 |● 121. 买卖股票的最佳时机 ● 122.买卖股票的最佳时机II

121. 买卖股票的最佳时机

dp数组需要记录两种状态,一种是当天时手中还持有股票,一种是当天时手中已卖出股票。

func maxProfit(prices []int) int {dp := make([][]int, len(prices))dp[0] = []int{-prices[0], 0}for i := 1; i < len(prices); i++{val0 := max(dp[i - 1][0], -prices[i])val1 := max(dp[i - 1][1], prices[i] + dp[i - 1][0]) dp[i] = []int{val0,val1}} return dp[len(prices) - 1][1]
}func max(a ,b int)int{if a < b{return b}return a
}

122.买卖股票的最佳时机II

持有股票的状态可以是当天才持有,也可以是之前就持有
卖出的状态同理

func maxProfit(prices []int) int {dp := make([][]int, len(prices))dp[0] = []int{-prices[0], 0}for i := 1; i < len(prices); i++{val0 := max(dp[i - 1][0], dp[i - 1][1] - prices[i])val1 := max(dp[i - 1][0] + prices[i], dp[i - 1][1])dp[i] = []int{val0, val1}}return dp[len(prices) - 1][1]
}
func max(a, b int)int{if a < b{return b}return a
}
http://www.lryc.cn/news/150920.html

相关文章:

  • SQLserver基础入门理论(超基础)
  • (三)行为模式:7、观察者模式(Observer Pattern)(C++示例)
  • 2019CVPR Semantic Graph Convolutional Networks for 3D Human Pose Regression
  • 大数据课程K16——Spark的梯度下降法
  • springboot:时间格式化的5种方法(解决后端传给前端的时间格式转换问题)推荐使用第4和第5种!
  • 六、vim编辑器的使用
  • 【易售小程序项目】项目介绍与系列文章集合
  • 游戏服务器成DDoS最大攻击重灾区
  • [SpringBoot3]博客管理系统(源码放评论区了)
  • C语言——指针基本语法
  • elementui table 在浏览器分辨率变化的时候界面异常
  • 六、Kafka-Eagle监控
  • DBeaver 23.1.5 发布
  • 三种垃圾收集算法,优缺点分析,设计垃圾收集
  • 【链表OJ 10】环形链表Ⅱ(求入环节点)
  • RT-Thread在STM32硬件I2C的踩坑记录
  • 小白学Go基础01-Go 语言的介绍
  • Spring工具类--Assert的使用
  • 无涯教程-Android - Absolute Layout函数
  • 2018ECCV Can 3D Pose be Learned from2D Projections Alone?
  • 干旱演变研究:定义及研究方法
  • 【LeetCode-中等题】114. 二叉树展开为链表
  • 【题解】JZOJ6645 / 洛谷P4090 [USACO17DEC] Greedy Gift Takers P
  • Vue 项目中的错误如何处理的?
  • 网络分层的真实含义
  • RT-Thread 线程间同步
  • Python元类再解释
  • 常用的Spring Boot 注解及示例代码
  • react app教程
  • 在vue项目中用vue-watermark快捷开发屏幕水印效果