*leetcode #123 in cpp
来源:互联网 发布:淘宝在国外能用吗 编辑:程序博客网 时间:2024/06/06 00:00
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).
Since we can make at most 2 transactions, we can divide the array into two parts, each part contains a transaction. Then we get maximum profit from left part, and maximum profit from right part. Then we have total profit = left profit + right profit. We want to maximize the total profit, and thus we should try every left part [0....i], i = 0,...,n, calculate the total profit and get the maximum total profit.
Code:
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int n = prices.size(); vector<int> leftProfit(n,0); //leftProfit[i] = max profit we can get from day 0 to day i. vector<int> rightProfit(n,0);//rightProfit[i] = max profit we can get from day i to day n int profit = 0; int cost = prices[0]; for(int i = 0; i < n; i ++){ if(prices[i] >= cost ){ profit = max(prices[i] - cost, profit); }else{ cost = prices[i]; } leftProfit[i] = profit; } profit = 0; cost = prices[n-1]; for(int i = n-1; i >=0; i --){ if(prices[i] <= cost){ profit = max(cost - prices[i], profit); }else{ cost = prices[i]; } rightProfit[i] = profit; } profit = 0; for(int i = 0; i < n; i ++){ profit = max(profit, leftProfit[i]+rightProfit[i]); } return profit; }};
- *leetcode #123 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- php中的session用法
- 山寨Besiege(六)代码托管、重构
- word文档开头首字母取消自动检查大写
- 【QT学习】View和Model
- PS安装完成后出现请卸载重新安装
- *leetcode #123 in cpp
- VMWare提供了三种工作模式上网
- 日常小结-C++友元回忆
- Linux下修改MySQL数据库root用户的密码
- 日常小结-C++返回了类型的编程限制
- ROS indigo在Ubuntu上的安装教程
- Java邮件配置项详细说明
- JavaMail 保证邮件发送成功的方法总结
- 创建 Oozie 工作流 失败