您的位置:首页 > 编程语言 > C语言/C++

[LeetCode] Best Time to Buy and Sell Stock II

2015-08-13 17:04 639 查看


Best Time to Buy and Sell Stock II

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

解题思路:

题意为给定每天的股价,你可以进行任何次数的交易,但是不能同时拥有多个股。要求最大的利润是多少。

我们可以在每个波谷的时候买进,每个波峰的时候卖出,这样的利润最大。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len==0 || len==1){
return 0;
}
int result = 0;
for(int i=1; i<len; i++){
if(prices[i]>prices[i-1]){
result += prices[i] - prices[i-1];
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++