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

    }
相关推荐
im_AMBER20 分钟前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
鼾声鼾语1 小时前
matlab的ros2发布的消息,局域网内其他设备收不到情况吗?但是matlab可以订阅其他局域网的ros2发布的消息(问题总结)
开发语言·人工智能·深度学习·算法·matlab·isaaclab
LYFlied1 小时前
【每日算法】LeetCode 25. K 个一组翻转链表
算法·leetcode·链表
Swizard1 小时前
别再迷信“准确率”了!一文读懂 AI 图像分割的黄金标尺 —— Dice 系数
python·算法·训练
s09071361 小时前
紧凑型3D成像声纳实现路径
算法·3d·声呐·前视多波束
可爱的小小小狼1 小时前
算法:二叉树遍历
算法
d111111111d2 小时前
在STM32函数指针是什么,怎么使用还有典型应用场景。
笔记·stm32·单片机·嵌入式硬件·学习·算法
AI科技星3 小时前
质量定义方程常数k = 4π m_p的来源、推导与意义
服务器·数据结构·人工智能·科技·算法·机器学习·生活
摇摆的含羞草3 小时前
哈希(hash)算法使用特点及常见疑问解答
算法·哈希算法
仰泳的熊猫4 小时前
1077 Kuchiguse
数据结构·c++·算法·pat考试