【小熊刷题】Best Time to Buy and Sell Stock I <leetcode 121 Java>

本文探讨了一道经典的算法题目——买卖股票的最佳时机。通过两种不同的解决方案,分别采用O(N)时间和O(1)额外空间复杂度及O(N)时间和O(N)额外空间复杂度的方法,寻找给定股票价格数组中能够获得的最大利润。

看完书上不是premium的题了,正式开始刷题。

先来这个高频的买卖股票的题

Question

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

此题看似简单,但其实是在找一组数组里面最大差值,且最大值在最小值出现之后

在网上找到了相关的算法解答
http://www.geeksforgeeks.org/maximum-difference-between-two-elements/

一开始最简单的是brute force方法,但是O(N^2) OJ显然不满意,说超时了

于是第一种算法

solution 1

O(N), O(1)
遍历一遍,每次对比maxProfit和最小值,做相应改变

public class Solution {
    //observe min and maxProfit while traverse the array
    public int maxProfit(int[] prices) {
        if(prices.length <= 1) return 0;
        int min = prices[0]; int maxProfit = 0;
        for(int i = 1; i < prices.length; i++){
            if(prices[i]-min > maxProfit) maxProfit = prices[i]-min;
            if(prices[i] < min) min = prices[i];
        }
        return maxProfit;
    }
}

Solution 2

runtime O(n), space O(n)
把每个相邻价格的差存成array,然后如果一直增加就加起来,来找到最大profit

public class Solution {
    //observe min and maxProfit while traverse the array
    public int maxProfit(int[] prices) {
        if(prices.length <= 1) return 0;
        int[] diff = new int[prices.length-1];
        //find each adjacent diff
        for(int i = 0; i < prices.length-1; i++){
            diff[i] = prices[i+1] - prices[i];
        }
        int maxDiff = diff[0] >= 0 ? diff[0] : 0;
        for(int i = 1; i < prices.length-1; i++){
            if(diff[i-1] > 0) diff[i] += diff[i-1];
            if(diff[i] > maxDiff) maxDiff = diff[i];
        }
        return maxDiff;
    }
}

把之前的简化一些,可以变成space为O(1)的,如下:

public class Solution {
    //observe min and maxProfit while traverse the array
    public int maxProfit(int[] prices) {
        if(prices.length <= 1) return 0;

        int maxDiff = (prices[1] - prices[0] >= 0) ? prices[1] - prices[0] : 0;
        int diff = maxDiff; int currSum = maxDiff;

        for(int i = 1; i < prices.length-1; i++){
            diff = prices[i+1] - prices[i];
            if(currSum > 0) currSum += diff;
            else currSum = diff;
            if(currSum > maxDiff) maxDiff = currSum;
        }
        return maxDiff;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值