首页 > 代码库 > Best Time to Buy and Sell Stock

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

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.

答案

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length<=1)
        {
            return 0;
        }
        int currentProfit=0;
        int smallestPrice=prices[0];
        int LEN=prices.length;
        for(int i=1;i<LEN;i++){
            smallestPrice=Math.min(smallestPrice,prices[i]);
            currentProfit=Math.max(currentProfit,prices[i]-smallestPrice);
        }
        return currentProfit;
    }
}

Best Time to Buy and Sell Stock