java 买卖股票的最佳时机只做一笔交易

java 买卖股票的最佳时机只做一笔交易


public class Stock1
{
    public static int maxProfit(int prices[])
    {
        int min =  Integer.MAX_VALUE;  // 最小的谷值
        int val = 0;    //最大的利润
        for (int i = 0; i < prices.length; i++)
        {
            // 比最小值小
            if (prices[i] < min )
            {
                min = prices[i];// 把当前最小值赋值
            } 
            // 比最小值大
            else if (prices[i] - min > val )
            {

                val = prices[i] - min ;// 当前比最小值大,得出差值如果大于最大获利,就复制
            }
        }
        return val ;
    }

    
    public static void main(String[] args)
    {
        int[] prices =    { 7, 1, 5, 3, 6, 4 };
        int[] prices1 =    { 1, 2, 3, 4, 5 };
        int[] prices2 =    { 7, 6, 4, 3, 1 };
        int[] prices3 =    { 7, 6, 8, 3, 5, 6, 1 };
        // System.out.println(maxProfit2(prices));
        // System.out.println(maxProfit2(prices1));
        // System.out.println(maxProfit2(prices2));
        System.out.println(maxProfit(prices3));
    }
}