DAY41 股票问题

I

某天买入某天卖出

java 复制代码
    public int maxProfit(int[] prices) {
        int min=prices[0];
        int maxProfit=0;
        for(int i=1;i<prices.length;i++){
            if(prices[i]<min)min=prices[i];
            int profit=prices[i]-min;
            if(profit>maxProfit)maxProfit=profit;

        }
        return maxProfit;
    }

II

每天都可买入卖出

最多同时持有一只股票

java 复制代码
    public int maxProfit(int[] prices) {
        int []profit=new int[prices.length];
        int res=0;
        for(int i=1;i<prices.length;i++){
            profit[i]=prices[i]-prices[i-1];
            if(profit[i]>0)res+=profit[i];
        }
        return res;


    }

III

最多买卖两次

java 复制代码
    public int maxProfit(int[] prices) {
        int len=prices.length;

        int [][]dp=new int[len][5];
        dp[0][1]=-prices[0];
        dp[0][3]=-prices[0];
        for(int i=1;i<len;i++){
            
            dp[i][1]=Math.max(dp[i-1][1],0-prices[i]);
            dp[i][2]=Math.max(dp[i-1][2],dp[i-1][1]+prices[i]);
            dp[i][3]=Math.max(dp[i-1][3],dp[i-1][2]-prices[i]);
            dp[i][4]=Math.max(dp[i-1][4],dp[i-1][3]+prices[i]);
        }
        return dp[len-1][4];

    }
相关推荐
范特西_13 分钟前
两个无重叠子数组的最大和
c++·算法
可触的未来,发芽的智生22 分钟前
触摸未来2025.10.05:悟神经网络符号之伤,拥抱声音的宇宙
人工智能·python·神经网络·算法·架构
_bong39 分钟前
python评估算法性能
数据结构·python·算法
Mr.Ja2 小时前
【LeetCode 热题 100】No.49—— 字母异位词分组(Java 版)
java·算法·leetcode·字母异位词分组
未知陨落2 小时前
LeetCode:99.下一个排列
算法·leetcode
2401_841495642 小时前
【数据结构】链栈的基本操作
java·数据结构·c++·python·算法·链表·链栈
Archie_IT3 小时前
「深入浅出」嵌入式八股文—P2 内存篇
c语言·开发语言·数据结构·数据库·c++·算法
是那盏灯塔3 小时前
【算法】——动态规划算法及实践应用
数据结构·c++·算法·动态规划
MATLAB代码顾问3 小时前
MATLAB计算标准径流指数(Standard Runoff Index,SRI)
数据结构·算法·matlab
qq_574656254 小时前
java代码随想录day50|图论理论基础
java·算法·leetcode·图论