首页 > 其他 > 详细

Best Time to Buy and Sell Stock

时间:2014-05-09 13:13:24      阅读:485      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

会时间超时的一种解法,最差的时间复杂度位O(n*n)

bubuko.com,布布扣
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1)
            return 0;
        int max=0;
        boolean bo=true;
        for(int n=1;n<prices.length;n++){
            if(prices[n]>prices[n-1])
                bo = false;
        }
        if(bo)
            return 0;
        for(int i=0;i<prices.length-1;i++){
            int temp = FindMax(prices,i);
            if(temp!=prices[i]){
                int t = temp-prices[i];
                if(t>max)
                    max=t;
            }
        }
        return max;
    }

    private int FindMax(int[] prices, int i) {
        // TODO Auto-generated method stub
        int max = prices[i];
        for(int j=i+1;j<prices.length;j++){
            if(prices[j]>max)
                max = prices[j];
        }
        return max;
    }
}
bubuko.com,布布扣

另外一种优化的accept的解法

bubuko.com,布布扣
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1)
            return 0;
        int max = prices[prices.length-1];
        int re = 0;
        for(int i=prices.length-2;i>=0;i--){
            int temp = max-prices[i];
            if(temp>re)
                re = temp;
            if(prices[i]>max)
                max=prices[i];
        }
        return re;
    }
}
bubuko.com,布布扣

 

Best Time to Buy and Sell Stock,布布扣,bubuko.com

Best Time to Buy and Sell Stock

原文:http://www.cnblogs.com/yixianyixian/p/3718331.html

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