Max-Sum-Subarray - HackerRank JAVA

这是一篇关于解决HackerRank上'Max-Sum-Subarray'问题的博客。题目要求在给定整数数组中找到不含0的最长递增子序列,并计算其最大和。当遇到0时,子序列可以从0处重新开始。文章提到了简单的比较方法以及如何将问题转化为动态规划(DP)来求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

S - Max-Sum-Subarray

 HackerRank - max-sum-subarray 

因为有图片 复制不全

You are given an array  of  integers. 
You need to find the contiguous subarray of the maximum sum in . The subarray should not contain the number . Please find the maximum sum that is possible.

Note 1: The subarray can also be empty. 
Note 2: The answer will fit in 32 bit-signed integer.

Input Format

The first line contains the integer N. The next line contains  integers representing the numbers in the array.

Constraints

 

Output Format

Output a single line representing the maximum sum that can be obtained.

Sample Input

5   
3 4 0 1 2

Sample Output

7

Explanation

The subarray with the maximum sum that doesn't contain a 0 is 3,4
Hence, the sum is .7

一开始简单的比较0与0之间的序列哪个大

后来定睛一看,原来Ai可以是负数! 哈哈 就说不能那么简单

那么就转换为一个DP问题了

对于位置i,dp[i]为这个点的最大序列和

那么dp[i]=dp[i-1]+arr[i]  if dp[i-1]>=0

else dp[i] = arr[i]

import java.util.Scanner;

public class Main{
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		long arr[] = new long[n];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = sc.nextLong();
		}
		long ans = 0;
		for (int i = 0; i < arr.length; i++) {
			if(arr[i]>0) break;
		}
		long dp[] = new long[n];
		if(arr[0]==0) dp[0] = 0;
		else dp[0] = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if(arr[i]==0) dp[i]=0;
			else if(dp[i-1]>0) {
				dp[i] = dp[i-1]+arr[i];
			}else {
				dp[i] = arr[i];
			}
		}
		for (int i = 0; i < dp.length; i++) {
			if(dp[i]>ans) ans=dp[i];
		}
		System.out.println(ans);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值