首页 > 其他 > 详细

Best Time to Buy and Sell Stock III

时间:2014-02-19 18:31:51      阅读:261      评论:0      收藏:0      [点我收藏+]

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 at most two transactions.

bubuko.com,布布扣
 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         int len = prices.length;
 4         if(len==0) return 0;
 5         int res = 0;
 6         int[] profit = new int[len];
 7         int min = Integer.MAX_VALUE;
 8         int maxProfitBeforeI = 0;
 9         for(int i=0;i<len;i++){
10             int cur = prices[i];
11             if(min>cur){
12                 min = cur;
13             }
14             if(maxProfitBeforeI<cur-min){
15                 maxProfitBeforeI = cur-min;
16             }
17             profit[i] = maxProfitBeforeI;
18         }
19         int max = Integer.MIN_VALUE;
20         for(int i=len-1;i>=0;i--){
21             int cur = prices[i];
22             if(max<cur){
23                 max = cur;
24             }
25             if(max-cur>0){
26                 res = Math.max(res,profit[i]+max-cur);
27             }
28         }
29         return res;
30     }
31 }
View Code

Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/krunning/p/3555192.html

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