码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode| Best time to buy and sell stock 2

时间:2015-03-29 12:22:52      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   c++   

题目:

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).

思路:和上面的一样创建同样的数组,那么此题类似于求一个数组中都为正数的值的和。

int SellStock(vector<int>& vec)
{
	vector<int> share(vec.size(),0);
	int i;
	for(i=1;i<vec.size();i++)
		share[i] = vec[i]-vec[i-1];
	int sum=0;
	for(i=-0;i<share.size();i++)
		if(share[i]>0)
			sum+= share[i];
	return sum;
	
}


LeetCode| Best time to buy and sell stock 2

标签:leetcode   算法   c++   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/44725221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!