Best Time to Buy and Sell Stock II - LeetCode 4

来源:互联网 发布:网络语红烧肉什么意思 编辑:程序博客网 时间:2024/06/08 09:36

题目描述:

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是,收益为0。

以下是C++实现代码,用vector的下标或迭代器均可。

<span style="font-size:14px;">/*////////////////////12ms/////////////////////////////*/class Solution {public:    int maxProfit(vector<int>& prices) {        int sum = 0;        vector<int>::size_type len = prices.size();        if(len < 2)            return sum;                    vector<int>::size_type i = 1;        for(; i != len; i++)        {            if(prices[i] > prices[i-1])            {                sum += prices[i] - prices[i-1];            }        }        return sum;    }};/*//////////////////////12ms///////////////////////////*/class Solution {public:    int maxProfit(vector<int>& prices) {        int sum = 0;                if(prices.empty())            return sum;        for(vector<int>::iterator itr = prices.begin(); itr != prices.end()-1; itr++)        {            if(*itr < *(itr+1))            {                sum += *(itr+1) - *itr;            }        }        return sum;    }};</span>



0 0
原创粉丝点击