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

    }
相关推荐
m沐沐4 小时前
【深度学习】YOLOv2目标检测算法——改进点、网络结构与聚类先验框解析
人工智能·pytorch·深度学习·算法·yolo·目标检测·transformer
不会就选b4 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
geovindu5 小时前
go: Iterative Algorithms
开发语言·后端·算法·golang·迭代算法
Zachery Pole7 小时前
CCF-CSP备战NO.7【队列】
算法
闪电悠米7 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
满天星83035777 小时前
【算法】最长递增子序列(三种解法)
算法
啦啦啦啦啦zzzz8 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
清泓y10 小时前
RAG 技术
算法·ai
阿慧今天瘦了嘛10 小时前
计算机组成原理概述:从硬件到软件的桥梁
计算机网络·算法
网站优化(SEO)专家10 小时前
SEO核心算法拆解:网站排名快速提升的武林秘籍!
算法·搜索引擎·网站排名·核心算法