开始刷leetcode day12:Best Time to Buy and Sell Stock

来源:互联网 发布:演唱会市场怎样 知乎 编辑:程序博客网 时间:2024/06/07 03:37

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.



Java

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        int maxProfit = 0;
        int min = prices[0];
        for(int i=0; i<prices.length; i++)
        {
            if(prices[i]>min && (prices[i] - min > maxProfit))
            {
                maxProfit = prices[i] - min;
            }
            else if(prices[i] < min) min = prices[i];
        }
        
        return maxProfit;
    }
}

0 0