您的位置:首页 > 其它

[Leetcode 51] 122 Best Time to Buy and Sell Stock II

2013-05-26 02:27 573 查看
Problem:

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

Analysis:

As we mentioned in "Best Time to Buy and Sell Stock" problem, every day make a transaction can get the knowledge of how much profit you can have on every day. Since here we are allowed to make as many transactions as we like, we just need to make those transactions with profit and ignore others. Then we can make sure that we have the max profit.

Why this is right? Image you have three stock prices a, b, c

if you buy at a and sell at c, then the profit is: c - a = c-b+b-a = (c-b)+(b-a). This means it equals you buy on day a and sell on day b, and then buy on day b and then sell on day c. This example illustrates the cumulative property of profit. Thus every transaction can be divided into multiple one-day transactions. If any one of the one-day transaction has negative profit, the final result is not max. We just remove it from the transaction. After removing all the negative-profit transactions, the result is max.

Code:

class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (prices.size() == 0) return 0;

int tP, sum;
tP = 0;
for (int i=0; i<prices.size()-1; i++) {
sum = prices[i+1] - prices[i];
if (sum > 0)
tP += sum;
}

return tP;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: