LeetCode精选TOP面试题121.买卖股票的最佳时机

题目描述

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。
!!! 不能在买入股票前卖出股票 !!!

解题思路

思路1:一次遍历 O(N)

  • 1.维护两个整数,maxnum和minnum,用来记录区间最大值和最小值;

  • 2.遍历数组:

    • 当元素item 大于 maxnum 时,最大值mannum更新为item,此时比较最大值和最小值的差值 sub 当前记录的临时最大利润profit的大小关系,如果sub > profit,就更新profit,小於则不更新;
    • 当元素item 小于 minnum 时,最小值minnum和最大值maxnum都更新为item;
  • 3.遍历结束后直接返回profit。
    思路2:两层遍历,暴力求解 O(N²)
    两层遍历的过程中不断比较两数之差与profit的大小关系,更新找到最大利润,思路比较通俗易懂,但是时间复杂度高。

代码实现(Java)

/**
 * @author : flower48237
 * @2020/3/23 16:46
 * @title : LeetCode精选TOP面试题121.买卖股票的最佳时机
 */
public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0 || prices.length == 1){
            return 0;
        }
        // 法 1 ,一次遍历
        int maxnum = prices[0], minnum = prices[0];
        int profit= 0;
        for (int i = 1; i < prices.length; i++){
            if (prices[i] > maxnum){
                maxnum = prices[i];
                if (maxnum - minnum > profit){
                    profit= maxnum - minnum;
                }
            }
            if (prices[i] < minnum){
                minnum = prices[i];
                maxnum = prices[i];
            }

        }
        return profit;

		/* 法 2 暴力求解
        int maxprofit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxprofit)
                    maxprofit = profit;
            }
        }
        return maxprofit;
        */
         
    }
}

做完题之后膜拜大佬的解题思路,果然我是白痴级别,大佬的解题思路实在是太强了。
labuladong大佬的文章:一个方法团灭 6 道股票问题

ivan_allen大佬的文章:dp 7 行简约风格

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章