LeetCode 122. Best Time to Buy and Sell Stock II

题目: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).

Example 1:


Example 2:


Example 3:

 

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

思路:dp[i] 表示第i天能获得的最大收益。

状态转移:dp[i] = max{ dp[i] , dp[j-1] + prices[i]-prices[j] ( j = 1...i-1 )  }

第i天能获得最大收益:在前面 某 j 天买进东西,在第i天卖出得到的收益 再加上 j天之前的收益就是dp[j-1] ,或者直接不卖,dp[i] = dp[i-1]

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];
        
    }
};

 

posted @ 2018-07-16 11:31  Shendu.CC  阅读(181)  评论(0编辑  收藏  举报