【leetcode】BestTimetoBuyandSellStockII
Quesion :
Say you have an array for which the
i
th
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).
for example: array[] = { 2, 5, 3, 8, 9, 4 } , maxProfit = (9-8) + (8-3) + (5-2) = 1 + 5 + 2 = 8.
Anwser 1: :
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size() == 0) return 0; int len = prices.size(); int ret = 0; for(int i = len - 1; i > 0; i--){ if(prices[i] > prices[i-1]){ ret += prices[i] - prices[i-1]; } } return ret; } };
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-04-21 20:46:53
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!