描述
Say you have an array for which the i-th 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).
#include<iostream>
using namespace std;
int SellStockII(int a[], int n)
{
if (a == NULL || n <= 1)
return 0;
int sum = 0;
for (int i = 0; i < n - 1; i++)
if (a[i + 1]>a[i])
sum += a[i + 1] - a[i];
return sum;
}
int main()
{
const int n = 6;
int a[n] = { 2, 4, 1, 5, 3, 4 };
int maxsum = SellStockII(a, n);
cout << maxsum << endl;
}