123.leetcode Best Time to Buy and Sell Stock III(hard)[动态规划算法 数组]
来源:互联网 发布:star法则java简历范文 编辑:程序博客网 时间:2024/06/06 05:35
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).
Subscribe to see which companies asked this question
具体思路:这道题的含义首先是最多只能进行两次交易,因此不像可以无上限交易的Best Time to Buy and Sell Stock II一样采用贪心的策略,应该选择一个合适的第一次交易与第二次交易的分界点。这里采用两个动态数组来完成,第一个dp1保存从0开始到i为止获得的一次交易的最大利益,dp2保存从i开始到n-1为止获得的一次交易的最大利益。最后的最大利益就是对每个i节点dp1[i]+dp2[i]的和最大的i节点。
class Solution {public: int getMax(int a,int b) { if(a>b) return a; else return b; } int maxProfit(vector<int>& prices) { //动态规划,采用两个状态标识,一个是dp1[n]表示在dp[i]之前的最大收益与I那个算法差不多,dp2[n]表示dp[i]之后一次交易的最大收益 int result = 0; int n = prices.size(); if(n<=1) return 0; int dp1[n]; int dp2[n]; memset(dp1,0,sizeof(dp1)); memset(dp2,0,sizeof(dp2)); int start = prices[0]; for(int i= 1;i<n;i++) { if(start > prices[i]) start = prices[i]; dp1[i] = getMax(dp1[i-1],prices[i]-start); } int last = prices[n-1]; for(int i= n-2;i>=0;i--) { if(last<prices[i]) last = prices[i]; dp2[i] = getMax(dp2[i+1],last-prices[i]); } for(int i=0;i<n;i++) { if((dp1[i]+dp2[i])>result) result = dp1[i]+dp2[i]; } return result; }};
0 0
- 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(W9):123. Best Time to Buy and Sell Stock III(动态规划)
- Leetcode 123. Best Time to Buy and Sell Stock III (Hard) (cpp)
- 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
- 面向对象(继承-final)day08
- 如何利用excel中的数据源制作数据地图
- Log 工具类
- 性能测试如何计算并发用户数
- WebLogic自保护之一:让WebLogic免于过载之苦
- 123.leetcode Best Time to Buy and Sell Stock III(hard)[动态规划算法 数组]
- Windows调试工具入门 — windebug
- Guess Number Higher or Lower
- Java/Jsp中让数值不使用科学计数法显示的解决方案
- 同步直播(1):什么是空间度量以及统计?
- java程序调用linux脚本
- 软件测试分类
- 【JS&Html】一些总结
- 安卓学习笔记---使用Eclise与Idea时常使用的快捷键