当前位置:网站首页>53. 最大子数组和:给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
53. 最大子数组和:给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
2022-07-05 13:19:00 【?abc!】
题目描述
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [5,4,-1,7,8]
输出:23
提示:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
思路
使用动态规划的思想:
- 直接看代码,一模了然
代码
class Solution {
public int maxSubArray(int[] nums) {
//初始化
//pre表示到目前为止相加后,最大的值
//maxAns表示连续相加最大的值
int pre = 0, maxAns = nums[0];
//循环数组
for(int x : nums){
//当前值,与当前值和前面的值相加的结果进行比较
pre = Math.max(pre + x, x);
//得到到目前为止最大的值
maxAns = Math.max(maxAns,pre);
}
return maxAns;
}
}
代码说明
注释见。。。
边栏推荐
- 先写API文档还是先写代码?
- 简单上手的页面请求和解析案例
- SAE international strategic investment geometry partner
- 国际自动机工程师学会(SAE International)战略投资几何伙伴
- uni-app开发语音识别app,讲究的就是简单快速。
- 前缀、中缀、后缀表达式「建议收藏」
- 私有地址有那些
- Notion 类笔记软件如何选择?Notion 、FlowUs 、Wolai 对比评测
- Android本地Sqlite数据库的备份和还原
- The Research Report "2022 RPA supplier strength matrix analysis of China's banking industry" was officially launched
猜你喜欢

Get to know linkerd project for the first time

LB10S-ASEMI整流桥LB10S

C object storage

jenkins安装

Hundred days to complete the open source task of the domestic database opengauss -- openguass minimalist version 3.0.0 installation tutorial

Win10——轻量级小工具

蜀天梦图×微言科技丨达梦图数据库朋友圈+1

一文详解ASCII码,Unicode与utf-8

The Research Report "2022 RPA supplier strength matrix analysis of China's banking industry" was officially launched

MMSeg——Mutli-view时序数据检查与可视化
随机推荐
前缀、中缀、后缀表达式「建议收藏」
Rocky basics 1
CAN和CAN FD
It's too convenient. You can complete the code release and approval by nailing it!
同事半个月都没搞懂selenium,我半个小时就给他整明白!顺手秀了一波爬淘宝的操作[通俗易懂]
mysql获得时间
今年上半年,通信行业发生了哪些事?
MySQL splits strings for conditional queries
leetcode 10. Regular Expression Matching 正则表达式匹配 (困难)
将函数放在模块中
Integer ==比较会自动拆箱 该变量不能赋值为空
Default parameters of function & multiple methods of function parameters
leetcode:221. Maximum square [essence of DP state transition]
Principle and configuration of RSTP protocol
Changing JS code has no effect
go map
Rocky基础命令3
Overflow toolbar control in SAP ui5 view
【MySQL 使用秘籍】一网打尽 MySQL 时间和日期类型与相关操作函数(三)
Natural language processing series (I) introduction overview