【leetcode 121】Best Time to Buy and Sell Stock

题目:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

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.

解题思路:

在给定的数组中,找出前后两个数字相差最大的值(可以不相邻),把这个差值输出出来。

 

第一种解法:

    public int maxProfit(int[] prices) {
        if (prices.length < 2) {
            return 0;
        }
        int[] result = new int[prices.length];
        Arrays.fill(result, 0);
        for (int i = 0; i < prices.length; i++) {
            for (int j = 0; j < i; j++) {
                int temp = prices[i] - prices[j];
                if (temp > 0 && result[i] < temp) {
                    result[i] = temp;
                }
            }
        }
        Arrays.sort(result);
        return result[result.length - 1];
    }

这是自己一开始的解法,想要采取动态规划的方法,对数组本身进行二次遍历,把每一个数的最大差值都求出来,放在新的数组中,最后数组中的最大的数,即为最大差值。

后面又参考了网上大神的思路

第二种解法:

    public int maxProfit(int[] prices) {
        int ans = 0;
        // 边界值判断
        if (prices.length == 0) {
            return ans;
        }
        // 默认第一个为买入的值
        int bought = prices[0];
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > bought) {
                // 如果后面的数大于前面的数并且后面的数和前面数的差大于之前记录的差值
                if (ans < (prices[i] - bought)) {
                    // 使用当前差值替换现有差值
                    ans = prices[i] - bought;
                }
            } else {
                // 后面的数小于前面的数,用小的数替换买入值
                bought = prices[i];
            }
        }
        return ans;
    }

对于这道题来讲,只要自身遍历一遍,把数组中的最大最小值获取到,返回两者的差值。无论是空间复杂度还是时间复杂度都做到了简化。

时间复杂度:O(n^2)-->O(n)

空间复杂度:虽然都是O(n),但是第二种方式减少了记录差值的数组

 

学无止境,向大神看齐~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值