leetcode--Best Time to Buy and Sell Stock II

1.题目描述:

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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

2.解法分析:

有了上一篇文章的铺垫,这个问题很好解决,唯一需要注意的是题目中的一句话:However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again),before的含义很模糊,如果在一个时间点i卖出股票之后依然可以在时间点i买入股票,那么题目很简单,既然允许多次交易,直接求出查分数组里面所有正数的和即可。这个思路的代码是这样的:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() <= 1)return 0;
        vector<int>::iterator iter;
        
        int max=0;
        for(iter=prices.begin();iter!=prices.end()-1;++iter)
        {
            *iter = *(iter+1) - *iter;
            if(*iter>0)max+=*iter;
        }     
        return max;      
    }
};
提交结果之后运行正确,说明的确可以在第i天卖出之后继续买入:
image
ps : 实际上,如果第i天卖出之后不允许当天买入,这个问题也是有解的,只是稍微麻烦一些,代码如下:
 
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() <= 1)return 0;
        vector<int>::iterator iter;
        for(iter=prices.begin();iter!=prices.end()-1;++iter)
        {
            *iter = *(iter+1) - *iter;
        }
        
        prices.pop_back();
        
        
        return maxDiffSum(prices,0);
        
        
        
    }
private:
    int maxDiffSum(vector<int> &prices,int index)    
    {
        if(index >= prices.size())return 0;
        if(prices[index]<0)return maxDiffSum(prices,index+1);
        return max(maxDiffSum(prices,index+1),maxDiffSum(prices,index+2)+prices[index]);
    }
};

你可能感兴趣的:(LeetCode)