LeetCode14_买卖股票系列(暴力搜索、贪心、动态规划)

买卖股票系列问题


  • 买卖股票的最佳时机
  • 买卖股票的最佳时机||
  • 买卖股票的最佳时机|||
  • 买卖股票的最佳时机|V
  • 最佳买卖股票的时机含冷冻期
  • 买卖股票的最佳时机含手续费

一、题目描述

1.0买卖股票的最佳时机

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。

注意:你不能在买入股票前卖出股票。

在这里插入图片描述

1.1我的解答

暴力就完了,将所有的利润情况全计算出来,取最大值

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        if(prices == null || prices.length == 1){
    
    
            return 0;
        }
        List<Integer> ml = new ArrayList<>();
        

        for(int i = 0;i<prices.length ;i++){
    
    
            for(int j = i + 1;j<prices.length;j++){
    
    
               if(prices[j] > prices[i]){
    
    
                    ml.add(prices[j] - prices[i]);
                }   
            }
        }
        return ml.isEmpty()?0:Collections.max(ml);
    }
}

1.2题解之一次遍历

假如计划在第 i 天卖出股票,那么最大利润的差值一定是在[0, i-1] 之间选最低点买入;

所以遍历数组,依次求每个卖出时机的的最大差值,再从中取最大值。

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;
    }
}

1.3题解之动态规划

DP有时间在淦!

public class Solution {
    
    

    public int maxProfit(int[] prices) {
    
    
        int len = prices.length;
        // 特殊判断
        if (len < 2) {
    
    
            return 0;
        }
        int[][] dp = new int[len][2];

        // dp[i][0] 下标为 i 这天结束的时候,不持股,手上拥有的现金数
        // dp[i][1] 下标为 i 这天结束的时候,持股,手上拥有的现金数

        // 初始化:不持股显然为 0,持股就需要减去第 1 天(下标为 0)的股价
        dp[0][0] = 0;
        dp[0][1] = -prices[0];

        // 从第 2 天开始遍历
        for (int i = 1; i < len; i++) {
    
    
            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[len - 1][0];
    }
}


1.4题解之贪心

针对这道问题的特殊解答,贪心算法 在每一步总是做出在当前看来最好的选择。

该算法仅可以用于计算,但 计算的过程并不是真正交易的过程,但可以用贪心算法计算题目要求的最大利润。

public class Solution {
    
    

    public int maxProfit(int[] prices) {
    
    
        int len = prices.length;
        if (len < 2) {
    
    
            return 0;
        }

        int res = 0;
        for (int i = 1; i < len; i++) {
    
    
            res += Math.max(prices[i] - prices[i - 1], 0);
        }
        return res;
    }
}


有时间接着肝

剩下的参考:LeetCode题解

猜你喜欢

转载自blog.csdn.net/qq_24654501/article/details/111350074
今日推荐