LeetCode每日一题:买卖股票的最好时机 1

问题描述

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

问题分析

只买卖一次股票,求最大利润,相当于查找数组中最大差值
在这个数组中寻找最小值,但是要满足卖要在买之后,所以用利润代替最大值

代码实现

public int maxProfit(int[] prices) {
        if (prices.length == 0) return 0;
        int profit = 0;
        int min = prices[0];
        for (int i = 0; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            profit = Math.max(profit, prices[i] - min);
        }
        return profit;
    }

你可能感兴趣的:(LeetCode每日一题:买卖股票的最好时机 1)