leetcode:股票的最大利润(四)

66 阅读2分钟

题目:

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

示例 1:

 输入: [7,1,5,3,6,4] 

输出: 5 

解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 

思路一:一次遍历(也有dp算法的影子)

假设给定的数组为:[7, 1, 5, 3, 6, 4]

如果我们在图表上绘制给定数组中的数字,我们将会得到:

我们肯定会想:如果我是在历史最低点买的股票就好了!

太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。

那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。 

因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。  

要注意:历史最低点随着天数的推移,时可能变的!也相当于一个dp的过程。

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

//by LeetCode-Solution

思路二:dp算法动态规划

复杂度分析: 

时间复杂度 O(N)O(N) : 其中 NN 为 pricesprices 列表长度,动态规划需遍历 pricesprices 

空间复杂度 O(1)O(1) : 变量 costcost 和 profitprofit 使用常数大小的额外空间

class Solution {
    public int maxProfit(int[] prices) {
        int cost = Integer.MAX_VALUE, profit = 0;
        for(int price : prices) {
            cost = Math.min(cost, price);
            profit = Math.max(profit, price - cost);
        }
        return profit;
    }
}

//by:jyd