Leetcode(W9):123. Best Time to Buy and Sell Stock III(动态规划)
来源:互联网 发布:淘宝评价语100字 编辑:程序博客网 时间:2024/05/22 14:07
leetcode中Best Time to Buy and Sell Stock买卖股票的最佳时间总共有5道类型题。
1. Best Time to Buy and Sell Stock III
介绍:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题意:
给定一个数组,下标代表第几天,元素值即为当天可买进或卖出的股票价格,现在设定我们最多能进行2次交易(注意每次卖都必须卖光,不能说我今天1块钱买入明天2块钱卖出,后天又能3块钱卖出,一次交易只能一次买对应一次卖),谋取最大利益然后输出这个最大利益。
思路:
由于有了IV的思路,传送门在此,所以这道题直接用IV的解法令K为2即可。
这里主要讲一下用二维数组的做法,在IV中说了一维数组更方便好用,确实如此,因此貌似IV有一个样例你用二维数组会RT,也不知道是不是内存炸掉了,好吧反正就是我用二维数组做不出来囧,不过二维数组做一做K为2的情况还是可以的。
2. 代码
class Solution {public: int maxProfit(vector<int> &prices) { if (prices.empty()) return 0; int n = prices.size(), g[n][3] = {0}, l[n][3] = {0}; for (int i = 1; i < prices.size(); ++i) { int diff = prices[i] - prices[i-1]; for (int j = 1; j <= 2; ++j) { l[i][j] = max(g[i-1][j-1] + max(diff, 0), l[i-1][j] + diff); g[i][j] = max(l[i][j], g[i-1][j]); } } return g[n-1][2]; }};
阅读全文
0 0
- Leetcode(W9):123. Best Time to Buy and Sell Stock III(动态规划)
- Leetcode(W9):188. Best Time to Buy and Sell Stock IV(动态规划)
- 123.leetcode Best Time to Buy and Sell Stock III(hard)[动态规划算法 数组]
- LeetCode 123. Best Time to Buy and Sell Stock III| 动态规划
- LeetCode 123. Best Time to Buy and Sell Stock III(动态规划)
- LeetCode--Best Time to Buy and Sell Stock III (动态规划)
- LeetCode动态规划思想:Best Time to Buy and Sell Stock III
- LeetCode 123. Best Time to Buy and Sell Stock III
- [Leetcode]123.Best Time to Buy and Sell Stock III
- [Leetcode] 123. Best Time to Buy and Sell Stock III
- [leetcode] 123.Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- [leetcode] 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- leetcode 123. Best Time to Buy and Sell Stock III
- [LeetCode] 123. Best Time to Buy and Sell Stock III
- Leetcode 123. Best Time to Buy and Sell Stock III
- 【leetcode】123. Best Time to Buy and Sell Stock III
- Vue.js组件——组件的基础知识
- CMake入门---最简单的helloworld程序
- XSS攻击测试代码
- gst-rtsp-server 转发服务器的搭建
- haproxy检测页面参数解释
- Leetcode(W9):123. Best Time to Buy and Sell Stock III(动态规划)
- 用jquery插件写一个小米官网左侧二级菜单
- 上拉刷新下拉加载
- SpringAOP导致@Autowired依赖注入失败
- C++ vector用法总结
- Invert a Binary Tree (25)
- python 聊天机器人 ,编译为exe
- 素数对猜想
- 1017. A除以B (20)