Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Input2: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
问题分析:
c++代码
#include<iostream>
using namespace std;#include<vector>#include<algorithm>
class Solution
{
public:intmaxProfit(vector<int>& prices){int res =0;for(auto i =0; i < prices.size()-1; i++){
res +=max(prices[i +1]- prices[i],0);}return res;}};intmain(int argc,char* argv[]){
vector<int> prices ={1,2,3,4,5,6};
Solution solution;
cout << solution.maxProfit(prices)<< endl;system("pause");return0;}
leet_code:链接问题描述:有一个数组,第i个元素代表第i天的股票价格,设计一个算法计算该股票收益的最大值,可以尽可能多的进行交易,但你必须没掉一只股票后才可以买另一只股票。输入输出样例:Input1: [7,1,5,3,6,4]Output1: 7Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = ...