Say you have an array for which the i thelement is the price of a given stock on dayi.
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).
题意:
用一个数组表示股票每天的价格,数组的第i个数表示
股票在第i天的价格,交易次数不限,但一次只能交易一支
股票,也就是说手上最多只能持有一支股票,求最大受益
思路:贪心算法
从前向后遍历数组,只要当天的价格高于前一天的价格,就算收益
class Solution
{
int maxProfit(vector<int> &prices)
{
if (prices.size()<2)
{
return 0;
}
int max = 0;
for (int i = 1; i<prices.size(); i++)
{
int diff = prices[i] - prices[i - 1];
if (diff>0)
{
max += diff;
}
}
return max;
}
};