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

    }
相关推荐
地平线开发者10 分钟前
Horizon 模型多 Batch 配置
算法·自动驾驶
czhaii22 分钟前
GB2312简体中文编码表
单片机·算法
8Qi831 分钟前
LeetCode 121 & 122:股票买卖问题(DP 对比题解)✅
算法·leetcode·职场和发展·动态规划
一只齐刘海的猫42 分钟前
【Leetcode】 接雨水
java·算法·leetcode
南境十里·墨染春水1 小时前
讲讲移动语义
算法
西凉的悲伤1 小时前
Guava类库——Range连续区间
java·算法·guava
菜菜的顾清寒1 小时前
力扣HOT(100)54多维动态规划-最长公共子序列
算法·leetcode·动态规划
随意起个昵称1 小时前
线性dp-LIS题目3(合唱队形)
算法
小六学编程1 小时前
二分查找详解:从普通二分到左右边界
算法·c/c++
wayz111 小时前
Volume:PVO(百分比成交量震荡指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程