leetcode------Best Time to Buy and Sell Stock II

标题: Best Time to Buy and Sell Stock II
通过率: 37.3%
难度: 中等

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

我感觉这道题目还是没有描述清楚,与第一个版本相似,这道题可以多次购买和卖出求最大值,刚开始我以为是手里可以购买两次然后再卖,那么本题就是每次求一个正序的最大最小,但是我发现手里不能同时持有多张股票,也就是说如果购买了一次。那么下一手只能是卖出了。这个题目就变成了贪心算法的题目。只要下一次比当前这一次价格高,那么就买入,然后下一次卖出,那么利润公式就是 result+=prices[i+1]-prices[i];

这个题目还有一个第三版本,但是是hard难度。我暂时不考虑,hard难度应该是用动态规划了。

一次遍历结果就出来了,直接看代码:

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

 

posted @ 2015-02-02 11:02  pku_smile  阅读(166)  评论(0编辑  收藏  举报