题目描述:
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).
Example
题目思路:
Given an example [2,1,2,0,1], return 2
如果可以不计次数的买入卖出,那么肯定是第一天买第二天看到高了就卖是最划算的。如果第二天反而低了,那么第一天就设定为不买(这两天的利润就是0)。所以这题的code很简单,就是一个差分呗。
Mycode(AC = 32ms):
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
if (prices.size() <= 1) return 0;
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
profit += max(0, prices[i] - prices[i - 1]);
}
return profit;
}
};