当前位置:网站首页>#yyds干货盘点# 解决名企真题:连续最大和
#yyds干货盘点# 解决名企真题:连续最大和
2022-07-04 12:44:00 【51CTO】
1.简述:
描述
一个数组有 N 个元素,求连续子数组的最大和。 例如:[-1,2,1],和最大的连续子数组为[2,1],其和为 3
输入描述:
输入为两行。 第一行一个整数n(1 <= n <= 100000),表示一共有n个元素 第二行为n个数,即每个元素,每个整数都在32位int范围内。以空格分隔。
输出描述:
所有连续子数组中和最大的值。
示例1
输入:
输出:
2.代码实现:
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sums=0, maxsums=Integer.MIN_VALUE; //考虑全为负数的情况
for(int i=0;i<n;i++){
sums+=sc.nextInt();
maxsums=Math.max(maxsums,sums);
sums= sums<0?0:sums; //代码核心了,如果当前求和为负,则抛弃之前的连续数组,重新开始求和
}
System.out.println(maxsums);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
边栏推荐
- Introduction to XML III
- Backgroundworker usage example
- Introduction to XML II
- Node mongodb installation
- 高效!用虚拟用户搭建FTP工作环境
- C#基础深入学习一
- .NET 使用 redis
- XILINX/system-controller-c/BoardUI/无法连接开发板,任意操作后卡死的解决办法
- AI painting minimalist tutorial
- The old-fashioned synchronized lock optimization will make it clear to you at once!
猜你喜欢

The only core indicator of high-quality software architecture

从0到1建设智能灰度数据体系:以vivo游戏中心为例
Efficient! Build FTP working environment with virtual users

PostgreSQL 9.1 soaring Road

When MDK uses precompiler in header file, ifdef is invalid

Interviewer: what is the difference between redis expiration deletion strategy and memory obsolescence strategy?

JVM系列——栈与堆、方法区day1-2

2022KDD预讲 | 11位一作学者带你提前解锁优秀论文

eclipse链接数据库中测试SQL语句删除出现SQL语句语法错误

After the game starts, you will be prompted to install HMS core. Click Cancel, and you will not be prompted to install HMS core again (initialization failure returns 907135003)
随机推荐
XML入门三
Xue Jing, director of insight technology solutions: Federal learning helps secure the flow of data elements
In 2022, it will be es2022 soon. Do you only know the new features of ES6?
FS4056 800mA充电ic 国产快充电源ic
Annual comprehensive analysis of China's mobile reading market in 2022
.NET 使用 redis
室外LED屏幕防水吗?
C#/VB. Net to add text / image watermarks to PDF documents
C语言个人通讯录管理系统
面试官:Redis 过期删除策略和内存淘汰策略有什么区别?
remount of the / superblock failed: Permission denied
Flet教程之 03 FilledButton基础入门(教程含源码)(教程含源码)
It is six orders of magnitude faster than the quantum chemical method. An adiabatic artificial neural network method based on adiabatic state can accelerate the simulation of dual nitrogen benzene der
C语言课程设计题
Comparative study of the gods in the twilight Era
"Pre training weekly" issue 52: shielding visual pre training and goal-oriented dialogue
After the game starts, you will be prompted to install HMS core. Click Cancel, and you will not be prompted to install HMS core again (initialization failure returns 907135003)
阿里云有奖体验:用PolarDB-X搭建一个高可用系统
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
面向个性化需求的在线云数据库混合调优系统 | SIGMOD 2022入选论文解读