122. Best Time to Buy and Sell Stock II

来源:互联网 发布:华讯网络北京怎么样 编辑:程序博客网 时间:2024/05/20 13:39

Say you have an array for which the ith element is the price of a given stock on dayi.

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).

Subscribe to see which companies asked this question

分析:

神鬼难测的算法。

假设a<b<c<d<e;

则应该返回ans=e-a=(e-d)+(d-c)+(c-b)+(b-a);

假设a<b>c<d<e;

则应该返回ans=e-c+b-a=(e-d)+(d-c)+0+(b-a);

代码如下:

class Solution {public:    int maxProfit(vector<int>& prices) {        int ret=0;        for(int i=1;i<prices.size();++i)        ret+=max(prices[i]-prices[i-1],0);        return ret;    }};


0 0
原创粉丝点击