Best-time-to-buy-and-sell-stock

题目描述


Say you have an array for which the i th 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.

code:
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length < 1)
            return 0;
        int max = 0;
        int min = prices[0];
        for(int i = 0 ; i < prices.length ; i++)
        {
            min = Math.min(min,prices[i]);
            max = Math.max(max,prices[i]-min);
        }
        return max;
    }
}
Be cautious that it should have the initial value, not just zero.

猜你喜欢

转载自blog.csdn.net/neo233/article/details/80751798