首页 > 其他 > 详细

Best Time to Buy and Sell Stock II 解答

时间:2015-09-21 06:59:43      阅读:304      评论:0      收藏:0      [点我收藏+]

Question

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

Solution

The key to this problem is to only consider local minimizer point and local maximizer point. And then add up sums. In this way, we avoid processing situation that transactions happen on one day.

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices == null || prices.length < 2)
 4             return 0;
 5         int result = 0, localMin = prices[0], localMax = prices[0], i = 0, length = prices.length;
 6         while (i < length) {
 7             // To find local minimizer point
 8             while (i < length - 1 && prices[i + 1] < prices[i])
 9                 i++;
10             localMin = prices[i];
11             
12             // To find local maximizer point
13             i++;
14             if (i == length) {
15                 localMax = prices[length - 1];
16             } else {
17                 while (i < length - 1 && prices[i + 1] > prices[i])
18                     i++;
19                 if (i < length - 1)
20                     localMax = prices[i];
21                 else if (i == length - 1)
22                     localMax = prices[length - 1];
23             }
24             result += (localMax - localMin);
25         }
26         return result;
27     }
28 }

 

Best Time to Buy and Sell Stock II 解答

原文:http://www.cnblogs.com/ireneyanglan/p/4825119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!