声明:原题目转载自LeetCode,解答部分为原创
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).
Solution :
思路:对于给定数组prices[], 根据 “买-卖-买-卖” 的规则,求最大收益,只需注意以下两点:
(1)假定 prices[] = {3, 6, 9, 8, 1, 5, 7}, 首次买的价格为3, 最理想的卖价为9,但 9 - 3 = (6 - 3) + (9 - 6),即此次理想受益相当于两次买卖的受益,即买3卖6 和 买6卖9。
(2)穷尽一切可能的交易能够获得最大利益,即对数组prices[],将任意两个满足“prices[ i ] < prices[ i + 1 ]”的数值之差 prices[ i + 1 ] - prices[ i ]作为收益,可求收益之和。
代码如下:
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int max_pro = 0;
for (int i = 1; i < prices.size(); i ++)
{
if(prices[i] > prices[i - 1])
{
max_pro += prices[i] - prices[i - 1];
}
}
return max_pro;
}
};
int main()
{
vector<int> prices;
prices.push_back(2);
prices.push_back(4);
prices.push_back(1);
Solution text;
cout << text.maxProfit(prices) << endl;
return 0;
}