题目:
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
原文地址:http://blog.csdn.net/yusiguyuan/article/details/44725221