【LeetCode】Best Time to Buy and Sell Stock

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)

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;
    }
}

另外一种优化的accept的解法

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;
    }
}
原文地址:https://www.cnblogs.com/yixianyixian/p/3718331.html