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).
思路:找出数组中相邻元素差累计和最大的多个序列即可。
比如[1,2,3,4,5,4,2,5],在这个序列中[1,2,3,4,5]和[2,5]为累计和为正数的序列,另外一个知识点就是5-1=(2-1)+(3-2)+(4-3)+(5-4)
代码:
int maxProfit(vector<int>& prices) { int res = 0; for(size_t i = 1; i < prices.size(); i++){ res += max(prices[i] - prices[i - 1], 0); } return res; }
另外一种实现:
int maxprofit(vector<int>& nums){ int res = 0; size_t n = nums.size(); for(size_t i = 1; i < n; i++){ if(nums[i] > nums[i - 1]){ res += nums[i] - nums[i - 1]; } } rerurn res; } //或者用while int maxprofit(vector<int>& nums){ int res = 0; size_t n = nums.size(); while(size_t i < n-1){ if(nums[i] > nums[i - 1]){ res += nums[i +1] - nums[i]; } i++; } rerurn res; }