前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 123. Best Time to Buy and Sell Stock III

LeetCode 123. Best Time to Buy and Sell Stock III

作者头像
ShenduCC
发布2018-07-24 16:07:45
3100
发布2018-07-24 16:07:45
举报
文章被收录于专栏:算法修养

题目链接:

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/

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 (i.e., you must sell the stock before you buy again).

这又是一道动态规划的题目:

c++

代码语言:javascript
复制
class Solution {
public:
    int dp[100005][2];
    int maxProfit(vector<int>& prices) {
        
        memset(dp,0,sizeof(dp));
        int l = prices.size();
        for(int i=1;i<l;i++)
        {
            for(int j=i-1;j>=0;j--)
            {
                dp[i][0] = max(dp[i][0],max(dp[j][0],prices[i]-prices[j]));
                if(i-3>=0&&j>=1&&dp[j-1][0]>0)
                dp[i][1] = max(dp[i][1],max(dp[j][1],dp[j-1][0]+prices[i]-prices[j]));
            }
        }
        
        return max(dp[l-1][0],dp[l-1][1]);
        
    }
};
代码语言:javascript
复制
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-07-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档