当前位置:网站首页>#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.
边栏推荐
猜你喜欢

Comparative study of the gods in the twilight Era

诸神黄昏时代的对比学习

CVPR 2022 | transfusion: Lidar camera fusion for 3D target detection with transformer

三星量产3纳米产品引台媒关注:能否短期提高投入产出率是与台积电竞争关键

CA: efficient coordinate attention mechanism for mobile terminals | CVPR 2021

8 expansion sub packages! Recbole launches 2.0!

Commvault 和 Oracle 合作,在 Oracle 云上提供 Metallic数据管理即服务

Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example

Golang sets the small details of goproxy proxy proxy, which is applicable to go module download timeout and Alibaba cloud image go module download timeout
Efficient! Build FTP working environment with virtual users
随机推荐
XML入门一
Apache服务器访问日志access.log设置
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
Simple understanding of binary search
Web knowledge supplement
"Tips" to slim down Seurat objects
Introduction to XML I
Commvault 和 Oracle 合作,在 Oracle 云上提供 Metallic数据管理即服务
SQL statement syntax error in test SQL statement deletion in eclipse linked database
Besides, rsync+inotify realizes real-time backup of data
JVM系列——栈与堆、方法区day1-2
MySQL three-level distribution agent relationship storage
实战:fabric 用户证书吊销操作流程
Read the BGP agreement in 6 minutes.
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
实时云交互如何助力教育行业发展
c#数组补充
iptables基础及Samba配置举例
. Net using redis
Reading cognitive Awakening