1. 程式人生 > >[Array]122. Best Time to Buy and Sell Stock II(obscure)

[Array]122. Best Time to Buy and Sell Stock II(obscure)

nbsp 實現 元素 you max -s script -1 times

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; }

[Array]122. Best Time to Buy and Sell Stock II(obscure)