当前位置: 首页 > backend >正文

LeetCode 解题思路 44(Hot 100)

在这里插入图片描述

解题思路:

  1. dp 数组的含义: 以 nums[i] 为结尾的最长递增子序列的长度。
  2. 递推公式: dp[i] = Math.max(dp[i], dp[j] + 1)。
  3. dp 数组初始化: dp[i] = 1。
  4. 遍历顺序: 从小到大去遍历,从 i = 1 开始,直到 i = nums.length - 1。
  5. 打印 dp 数组

Java代码:

class Solution {public int lengthOfLIS(int[] nums) {int[] dp = new int[nums.length];Arrays.fill(dp, 1);int result = 0;for (int i = 0; i < nums.length; i++) {for (int j = 0; j < i; j++) {if (nums[i] > nums[j]) {dp[i] = Math.max(dp[i], dp[j] + 1);}}result = Math.max(result, dp[i]);}return result;}
}

复杂度分析:

  • 时间复杂度: O( n 2 n^2 n2)。
  • 空间复杂度: O(1)。
    在这里插入图片描述

解题思路:

  1. 初始化变量​​:
  • maxProduct:记录全局的最大乘积,初始值为数组的第一个元素。
  • minProduct:记录当前的最小乘积,初始值为数组的第一个元素。
  • result:记录最终的结果,初始值为数组的第一个元素。
  1. 遍历数组​​: 对于每个元素 nums[i],我们需要考虑两种情况:
  • 如果 nums[i] 是正数,那么当前的最大乘积可能是 maxProduct ∗ * nums[i] 或 nums[i] 本身,而最小乘积可能是 minProduct ∗ * nums[i] 或 nums[i] 本身。
  • 如果 nums[i] 是负数,那么当前的最大乘积可能是 minProduct ∗ * nums[i] 或 nums[i] 本身,而最小乘积可能是 maxProduct ∗ * nums[i] 或 nums[i] 本身。
  • 为了统一处理这两种情况,我们可以先计算 nums[i]、maxProduct ∗ * nums[i] 和 minProduct ∗ * nums[i] 的值,然后取其中的最大值和最小值分别作为新的 maxProduct 和 minProduct。
  1. 更新结果​​: 在每次迭代中,更新 result 为 maxProduct 和 result 中的较大值。

  2. 返回结果​​: 遍历结束后,返回 result。

Java代码:

public class Solution {public int maxProduct(int[] nums) {int maxProduct = nums[0];int minProduct = nums[0];int result = nums[0];for (int i = 1; i < nums.length; i++) {int tempMax = Math.max(nums[i], Math.max(maxProduct * nums[i], minProduct * nums[i]));minProduct = Math.min(nums[i], Math.min(maxProduct * nums[i], minProduct * nums[i]));maxProduct = tempMax;result = Math.max(result, maxProduct);}return result;}
}

复杂度分析:

  • 时间复杂度: O(n)。
  • 空间复杂度: O(1)。
http://www.xdnf.cn/news/2067.html

相关文章:

  • 蛋白质大语言模型ESM介绍
  • ​Stable Diffusion:Diffusion Model
  • 深度学习实战106-大模型LLM+股票MCP Server的股票分析和投资建议应用场景
  • 软件研发管理方法工具总结
  • 15.ArkUI Checkbox的介绍和使用
  • 【智能硬件】【CES 2025】Bhaptics TactSuit X40和TactGlove,带你走进真实的虚拟世界
  • 数据库-少库多表与多库少表理论
  • NHANES指标推荐:PLP
  • 零基础快速搭建AI绘画网站!用Gradio玩转Stable Diffusion
  • ⭐Unity_Demolition Media Hap (播放Hap格式视频 超16K大分辨率视频 流畅播放以及帧同步解决方案)
  • C++23 新特性深度落地与最佳实践
  • 迁移学习(基础)
  • AOP与IOC的详细讲解
  • Linux上安装Mysql、Redis、Nginx
  • 常用SQL整理
  • kvm网卡发现的采集信息脚本COLT_CMDB_KVM_NETDISC.sh
  • 云服务器和独立服务器的区别在哪
  • 线程池总结
  • 东南亚与中东小游戏市场出海调研报告
  • Properties配置文件
  • Spring Boot 中使用 Feign 调用内网 IP 接口并记录入参与出参
  • springboot启动的端口如何终止
  • Web4.0身份革命:去中心化身份系统的全栈实现路径
  • 如何将 sNp 文件导入并绘制到 AEDT (HFSS)
  • IMX675-AAQR-C 索尼图像传感器 属于索尼 Starvis 2 系列,主打 高灵敏度、低噪声,适用于工业检测、安防监控、机器视觉等场景 提供数据手册
  • Cancer Cell|scRNA-seq + scTCR + 空间多组学整合分析,揭示CD8⁺ T细胞在免疫治疗中的“双路径” | 临床问题的组学解答
  • UR5 UR5e机器人URDF文件
  • 精华贴分享|【牛马课题】可转债多策略研究-1【基础篇】
  • Linux部署ragflow,从安装docker开始~
  • commix