首页 > 其他 > 详细

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

时间:2017-08-05 11:27:57      阅读:198      评论:0      收藏:0      [点我收藏+]

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)

原文:http://www.cnblogs.com/qinguoyi/p/7289566.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!