【leetcode刷题笔记】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 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         int answer = 0;
 5         if(prices.size() == 0)
 6             return 0;
 7         for(int i = 0;i < prices.size()-1;i++)
 8         {
 9             if(prices[i+1]>prices[i])
10                 answer += prices[i+1]-prices[i];
11         }
12         return answer;
13     }
14 };

我还问了这个问题:http://oj.leetcode.com/discuss/4082/why-do-i-have-to-add-if-prices-size-0-return-0

Java版本:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int sum = 0;
 4         for(int i = 0;i < prices.length-1;i++){
 5             if(prices[i+1] > prices[i])
 6                 sum += prices[i+1]-prices[i];
 7         }
 8         return sum;
 9     }
10 }

 

posted @ 2014-04-01 17:05  SunshineAtNoon  阅读(212)  评论(0编辑  收藏  举报