首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 122. Best Time to Buy and Sell Stock II

LeetCode 122. Best Time to Buy and Sell Stock II

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

题目:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/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 as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

这是一道很简单的动态规划题目:

c++

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

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

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

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

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