码迷,mamicode.com
首页 > 编程语言 > 详细

122. Best Time to Buy and Sell Stock II 买股票贪心算法

时间:2017-10-29 20:18:35      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:max   ever   style   tran   fit   complete   bsp   贪心   price   

122. Best Time to Buy and Sell Stock II


 

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 int maxProfit(vector<int> &prices) {
2     int ret = 0;
3     for (size_t p = 1; p < prices.size(); ++p) 
4       ret += max(prices[p] - prices[p - 1], 0);    
5     return ret;
6 }

 

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int profit = 0;
 5         for(int i = 1; i < prices.size(); i++)
 6         {
 7             if(prices[i-1] < prices[i])
 8             {
 9                 profit += prices[i] - prices[i-1];
10             }
11         }
12         return profit;
13     }
14 };

 

122. Best Time to Buy and Sell Stock II 买股票贪心算法

标签:max   ever   style   tran   fit   complete   bsp   贪心   price   

原文地址:http://www.cnblogs.com/xumh/p/7750867.html

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