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) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() == 0) return 0; int profit = - prices.at(0); for(int i = 0;i < prices.size();i++) { if(i == prices.size()-1) { profit += prices.at(i); } else { if(prices.at(i) >= prices.at(i+1)) { profit += prices.at(i) - prices.at(i+1); } } } return profit; } };

浙公网安备 33010602011771号