67.剑指Offer-股票的最大利润

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/89036103

题目描述

假设您有一个数组,其中第i个元素是第一天给定股票的价格。如果你只被允许完成至多一笔交易(即买一份,卖一份股票),设计一个算法来找到最大利润。请注意,在购买股票之前,您不能出售股票。

可以有一次买入和一次卖出,那么买入必须在前。求最大收益。

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解题思路

使用贪心策略,假设第 i 轮进行卖出操作,买入操作价格应该在 i 之前并且价格最低。

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

猜你喜欢

转载自blog.csdn.net/cuicanxingchen123456/article/details/89036103