码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock

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

标签:des   style   blog   class   code   java   

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

标签:des   style   blog   class   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!