[leetcode] Best Time to Buy and Sell Stock II

来源:互联网 发布:vb.net 新建文件夹 编辑:程序博客网 时间:2024/05/29 11:13

1.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 (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.

Analyse:

e.g. array:   5 3 2 1 6 7 9

So we should buy at 1, sell at 9 and have profit 9 -1 = 8.

That's to say we should buy at valley and sell at peak.

How to tell valley and peak? --->f(x)'s slope using g(x)

Definition: if f(x) == f(x-1) , g(x) = 0;

                       f(x) > f(x-1), g(x) = 1;

                       f(x) < f(x-1), g(x) = -1;

valley is the   point where g(x) turn to 1 from 0 or -1;

peak is the point where g(x) turn to -1 from 0 or 1;


Then, we should buy first and then sell. so we need a flag to indicate the operation.

At last, if we have a stock on our hand, we need to sell the stock.

NOTE: f(x) = f(x-1).......

3 Code:

  

int maxProfit(vector<int> &prices) {    if(prices.size() <= 1)    {        return 0;    }     const int BUY = 1;//1 for buy -1 for sell    const int SELL = -1;            int profit = 0;    int pre = 0;    int cur = 0;    int operation = BUY;         std::vector<int>::iterator it;    for (it = prices.begin()+1; it != prices.end() ; ++it)    {        if (*it > *(it - 1))        {            pre = cur;            cur = 1;        }        else if (*it < *(it - 1))        {            pre = cur;            cur = -1;        }        else        {            pre = cur;            cur = 0;        }        if (pre < cur && cur == 1 && operation == BUY)        {            profit -= *(it - 1);            operation = SELL;        }        if (pre > cur && cur == -1 && operation == SELL)        {            profit += *(it -1);            operation = BUY;        }    }    if (operation == SELL)    {        profit += *(--it);    }    return profit;    }

0 0
原创粉丝点击