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).
Subscribe to see which companies asked this question.
贪心算法
考虑出差集合,求出正数之和即可
更好理解:只要today>yesterday,今日买入昨日卖出
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size = prices.size();
if (size < 2)
return 0;
int res = 0;
int* delta = new int [size - 1];
for (int i = 0 ; i < size - 1 ; i ++)
delta[i] = prices[i+1] - prices[i];
for (int i = 0 ; i < size - 1 ; i ++)
{
if (delta[i] > 0)
res += delta[i];
}
return res;
}
};