leetcode 123. Best Time to Buy and Sell Stock III

本文介绍了一种使用动态规划算法解决股票交易中寻找最大利润的问题,特别针对允许进行最多两次交易的情况。通过前后两次动态规划过程,分别计算买低卖高的最大收益,最终找出全局最优解。

传送门

 

123. Best Time to Buy and Sell Stock III

 
QuestionEditorial Solution
  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一次。。。
 
 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int sz = prices.size();
 5         vector<int> left(sz + 1,0);
 6         int i;
 7         int mi = INT_MAX;
 8         for(i = 0;i < sz;i++){
 9             if(i != 0){
10                 left[i] = left[i - 1];
11             }
12             if(prices[i] < mi){
13                 mi = prices[i];
14             }
15             else{
16                 left[i] = max(left[i],prices[i] - mi);
17             }
18         }
19         
20         vector<int> right(sz + 1,0);
21         int ma = INT_MIN;
22         for(i = sz - 1;i >= 0;i--){
23             if(i != sz - 1){
24                 right[i] = right[i + 1];
25             }
26             if(prices[i] > ma){
27                 ma = prices[i];
28             }
29             else{
30                 right[i] = max(right[i],ma - prices[i]);
31             }
32         }
33         //for(i = 0;i < sz;i++){
34         //    printf(" i = %d left = %d right = %d\n",i,left[i],right[i]);
35         //}
36         
37         int ma_profile = left[sz - 1];
38         for(i = 0;i < sz - 1;i++){
39             ma_profile = max(ma_profile,left[i] + right[i + 1]);
40         }
41         return ma_profile;
42     }
43 };

 

转载于:https://www.cnblogs.com/njczy2010/p/5703761.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值