[LeetCode] Best Time to Buy and Sell Stock III
发布日期:2021-08-30 16:00:46
浏览次数:15
分类:技术文章
本文共 1918 字,大约阅读时间需要 6 分钟。
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).解题思路
建立两个数组left
和right
,分别存储某个元素左边和右边所能获得的最大收益。即left[i]
存储从[0, i]
范围的最大收益;right[i]
存储从[i, len - 1]
范围的最大收益。
实现代码
/***************************************************************** * @Author : 楚兴 * @Date : 2015/2/22 18:08 * @Status : Accepted * @Runtime : 16 ms******************************************************************/#include#include #include using namespace std;class Solution {public: int maxProfit(vector &prices) { int len = prices.size(); if (len == 0) { return 0; } vector left(len, 0); vector right(len, 0); int i = 0; int low = prices[0]; int profit = 0; while (i < len - 1) { if (prices[i] < low) { low = prices[i]; } else if (prices[i] >= prices[i + 1]) { profit = max(profit, prices[i] - low); } left[i] = profit; i++; } profit = max(profit, prices[i] - low); left[i] = profit; int high = prices[i]; profit = 0; while(i > 0) { if (prices[i] > high) { high = prices[i]; } else if (prices[i] <= prices[i - 1]) { profit = max(profit, high - prices[i]); } right[i] = profit; i--; } profit = max(profit, high - prices[i]); right[i] = profit; i = 0; int max_profit = 0; while (i < len) { max_profit = max(max_profit, left[i] + right[i]); i++; } return max_profit; }};int main(){ int num[] = { 1,2,3,4,5,6}; vector n(num, num + sizeof(num)/sizeof(int)); Solution s; int profit = s.maxProfit(n); cout< <
另一种解题思路可参考。
转载地址:https://blog.csdn.net/weixin_34038652/article/details/90622261 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月08日 06时59分00秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
反馈不足
2019-04-28
人生永远没有太晚的开始
2019-04-28
python 周日福利来了
2019-04-28
状态模式
2019-04-28
跳表SkipList
2019-04-28
跳跃表(Skip list)原理与java实现
2019-04-28
Java 常见的 30 个误区与细节
2019-04-28
MySQL的数据类型
2019-04-28
洛谷 P1886 滑动窗口 /【模板】单调队列
2019-04-28
洛谷 P3367 【模板】并查集
2019-04-28
【算法学习】高级数据结构2 种类并查集
2019-04-28
洛谷 P1525 关押罪犯【种类并查集】
2019-04-28
洛谷 P2024 [NOI2001]食物链【种类并查集】
2019-04-28
POJ 1703 Find them, Catch them【种类并查集】
2019-04-28
POJ 2492 A Bug‘s Life【种类并查集】
2019-04-28
POJ 2236 Wireless Network【并查集】
2019-04-28
LeetCode C++ 214. Shortest Palindrome【字符串】困难
2019-04-28
洛谷 P2580 于是他错误的点名开始了【字典树/Map】
2019-04-28
HDU 3336 Count the string【KMP的next数组性质】
2019-04-28