leetcode 123. Best Time to Buy and Sell Stock III
2016-07-25 15:41
309 查看
传送门
My Submissions
Total Accepted: 62311
Total Submissions: 230292
Difficulty: Hard
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
Hide Tags
Array Dynamic Programming
Show Similar Problems
思路:
思想来源于动态规划,如果以arr[i]为第二个投资点,那么,必须找到i-1前面的最大投资收益
so,,,左右各dp一次。。。
123. Best Time to Buy and Sell Stock III
QuestionEditorial SolutionMy Submissions
Total Accepted: 62311
Total Submissions: 230292
Difficulty: Hard
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
Hide Tags
Array Dynamic Programming
Show Similar Problems
思路:
思想来源于动态规划,如果以arr[i]为第二个投资点,那么,必须找到i-1前面的最大投资收益
so,,,左右各dp一次。。。
class Solution { public: int maxProfit(vector<int>& prices) { int sz = prices.size(); vector<int> left(sz + 1,0); int i; int mi = INT_MAX; for(i = 0;i < sz;i++){ if(i != 0){ left[i] = left[i - 1]; } if(prices[i] < mi){ mi = prices[i]; } else{ left[i] = max(left[i],prices[i] - mi); } } vector<int> right(sz + 1,0); int ma = INT_MIN; for(i = sz - 1;i >= 0;i--){ if(i != sz - 1){ right[i] = right[i + 1]; } if(prices[i] > ma){ ma = prices[i]; } else{ right[i] = max(right[i],ma - prices[i]); } } //for(i = 0;i < sz;i++){ // printf(" i = %d left = %d right = %d\n",i,left[i],right[i]); //} int ma_profile = left[sz - 1]; for(i = 0;i < sz - 1;i++){ ma_profile = max(ma_profile,left[i] + right[i + 1]); } return ma_profile; } };
相关文章推荐
- C++ PDFLib 8.0 中文输出
- Node.js EventEmitter
- virsh - brctl - common networking configurations used by libvirt
- spring中用p标签配置bean的属性
- POJ1002:487-3279 神奇的TLE
- Codeforces Round #364 (Div. 2) C. They Are Everywhere (窗口滑动)
- va_start, va_arg练习
- Toad for oracle挂接虚拟机oracle数据库出现ORA-12541问题解决
- Android 使用Vitamio打造自己的万能播放器(7)――在线播放(下载视频)
- 漫游测试
- 欢迎使用CSDN-markdown编辑器
- Pnetest - hackerone company list
- 映射的研究
- 组件开发指南
- psi and index do not match
- linux 设置时间(hadoop 对于时间要求比较高,所有在集群时特别要注意时间)
- lightoj 1033【区间DP/LCS】
- php数组转xml
- 7、Drools内部功能详细介绍
- openfire 安装