
LeetCode14_买卖股票系列(暴力搜索、贪心、动态规划)
发布日期:2021-05-07 20:40:39
浏览次数:27
分类:原创文章
本文共 2325 字,大约阅读时间需要 7 分钟。
买卖股票系列问题
- 买卖股票的最佳时机
- 买卖股票的最佳时机||
- 买卖股票的最佳时机|||
- 买卖股票的最佳时机|V
- 最佳买卖股票的时机含冷冻期
- 买卖股票的最佳时机含手续费
一、题目描述
1.0买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
注意:你不能在买入股票前卖出股票。
1.1我的解答
暴力就完了,将所有的利润情况全计算出来,取最大值
class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 1){ return 0; } List<Integer> ml = new ArrayList<>(); for(int i = 0;i<prices.length ;i++){ for(int j = i + 1;j<prices.length;j++){ if(prices[j] > prices[i]){ ml.add(prices[j] - prices[i]); } } } return ml.isEmpty()?0:Collections.max(ml); }}
1.2题解之一次遍历
假如计划在第 i 天卖出股票,那么最大利润的差值一定是在[0, i-1] 之间选最低点买入;
所以遍历数组,依次求每个卖出时机的的最大差值,再从中取最大值。
public class Solution { public int maxProfit(int prices[]) { int minprice = Integer.MAX_VALUE; int maxprofit = 0; for (int i = 0; i < prices.length; i++) { if (prices[i] < minprice) { minprice = prices[i]; } else if (prices[i] - minprice > maxprofit) { maxprofit = prices[i] - minprice; } } return maxprofit; }}
1.3题解之动态规划
DP有时间在淦!
public class Solution { public int maxProfit(int[] prices) { int len = prices.length; // 特殊判断 if (len < 2) { return 0; } int[][] dp = new int[len][2]; // dp[i][0] 下标为 i 这天结束的时候,不持股,手上拥有的现金数 // dp[i][1] 下标为 i 这天结束的时候,持股,手上拥有的现金数 // 初始化:不持股显然为 0,持股就需要减去第 1 天(下标为 0)的股价 dp[0][0] = 0; dp[0][1] = -prices[0]; // 从第 2 天开始遍历 for (int i = 1; i < len; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]); dp[i][1] = Math.max(dp[i - 1][1], -prices[i]); } return dp[len - 1][0]; }}
1.4题解之贪心
针对这道问题的特殊解答,贪心算法 在每一步总是做出在当前看来最好的选择。
该算法仅可以用于计算,但 计算的过程并不是真正交易的过程,但可以用贪心算法计算题目要求的最大利润。
public class Solution { public int maxProfit(int[] prices) { int len = prices.length; if (len < 2) { return 0; } int res = 0; for (int i = 1; i < len; i++) { res += Math.max(prices[i] - prices[i - 1], 0); } return res; }}
有时间接着肝
剩下的参考:
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2025年03月28日 06时26分59秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
聊聊我的五一小假期
2021-05-08
数据库三个级别封锁协议
2021-05-08
ACM/NCPC2016 C Card Hand Sorting(upc 3028)
2021-05-08
ubuntu学习笔记-常用文件、命令以及作用(hosts、vim、ssh)
2021-05-08
SLAM学习笔记-求解视觉SLAM问题
2021-05-08
程序员应该知道的97件事
2021-05-08
create-react-app路由的实现原理
2021-05-08
openstack安装(九)网络服务的安装--控制节点
2021-05-08
shell编程(六)语言编码规范之(变量)
2021-05-08
vimscript学习笔记(二)预备知识
2021-05-08
Android数据库
2021-05-08
HTML基础,块级元素/行内元素/行内块元素辨析【2分钟掌握】
2021-05-08
STM8 GPIO模式
2021-05-08
23种设计模式一:单例模式
2021-05-08
Qt中的析构函数
2021-05-08
三层框架+sql server数据库 实战教学-徐新帅-专题视频课程
2021-05-08
【单片机开发】智能小车工程(经验总结)
2021-05-08
【单片机开发】基于stm32的掌上游戏机设计 (项目规划)
2021-05-08
C++&&STL
2021-05-08