问题描述
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).
思路分析
上一个题目变化,给出每天股票价格,可以多次买入一股和卖出一股,但是买入之前必须要卖出之前持有的一股。计算在这段时间内的最大利润。只要第二天比前一天的价格高就卖出,简单的贪心,不放过任何一点利润。
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit, total = 0;
for(int i = 1; i < prices.size();i++){
if(prices[i] > prices[i-1]){
profit = prices[i] - prices[i-1];
total += profit;
}
}
return total;
}
};
时间复杂度:O(n) //n为vector的元素个数
反思
比较简单的一个题目。