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 len = prices.size(); int profit = 0; for(int i = 1; i < len; i++){ profit += max(prices[i]-prices[i-1], 0); } return profit; }};方法二:略麻烦
class Solution {public: int maxProfit(vector<int>& prices) { int i = 0; int j = 1; int len = prices.size(); int profit = 0; int pre; while(j < len){ pre = prices[j-1]; if(pre < prices[j]){ j++; if(j == len) profit += prices[j-1] - prices[i]; }else{ cout << pre << endl; profit += pre - prices[i]; i = j; j++; } } return profit; }};新闻热点
疑难解答