LeetCode-买卖股票的最佳时机121

买卖股票的最佳时机121

题目描述

在这里插入图片描述

思路

1.暴力法(O(N^2))

对每一个值,找后面的最大差值

class Solution {
    public int maxProfit(int[] prices) {
        //暴力法
        if(prices == null || prices.length == 0){
            return 0;
        }
        int res = 0;
        for(int i = 0; i < prices.length-1;i++){
            int temp = 0;
            for(int j = i+1; j < prices.length;j++){
                if(prices[j] > prices[i] && prices[j]-prices[i] > temp){
                    temp = prices[j] - prices[i];
                    res = temp > res ? temp : res;
                }
            }
        }
        return res;
    }
}

2.利用最低“谷”,一次遍历O(n)

在这里插入图片描述
我们维护一个minPrice 的变量,如果遍历到的数字比这个变量小,更新这个变量。
否则,看看 prices[i] - minPrice 的值是否比我们之前得到的 maxProfit 要大,如果大,就更新;否则,不更新。


class Solution {
    public int maxProfit(int[] prices) {
        //一次遍历
        if(prices == null || prices.length == 0){
            return 0;
        }
        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;
    }
}

3.通用方法解决股票问题

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

空间复杂度降到O(1)

    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0){
            return 0;
        }
        int n = prices.length;
        int dp_i_0 = 0;
        int dp_i_1 = Integer.MIN_VALUE;
        for(int i = 0 ; i < n;i++){
            dp_i_0 = Math.max(dp_i_0,dp_i_1+prices[i]);
            dp_i_1 = Math.max(dp_i_1,-prices[i]);
        }
        return dp_i_0;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值