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

    }
相关推荐
kyle~21 分钟前
排序---插入排序(Insertion Sort)
c语言·数据结构·c++·算法·排序算法
Boop_wu32 分钟前
[数据结构] 队列 (Queue)
java·jvm·算法
hn小菜鸡1 小时前
LeetCode 3643.垂直翻转子矩阵
算法·leetcode·矩阵
ゞ 正在缓冲99%…2 小时前
leetcode101.对称二叉树
算法
YuTaoShao2 小时前
【LeetCode 每日一题】3000. 对角线最长的矩形的面积
算法·leetcode·职场和发展
2zcode2 小时前
基于Matlab可见光通信系统中OOK调制的误码率性能建模与分析
算法·matlab·php
纵有疾風起3 小时前
数据结构中的排序秘籍:从基础到进阶的全面解析
c语言·数据结构·算法·排序算法
纪元A梦3 小时前
贪心算法应用:推荐冷启动问题详解
算法·贪心算法
听风说雨的人儿3 小时前
腾讯面试题之编辑距离
算法
Lululaurel3 小时前
机器学习系统框架:核心分类、算法与应用全景解析
人工智能·算法·机器学习·ai·分类