Prepin
Log in

Create a program that outputs the longest consecutive positive sequence found within a specified array.

Approach / Explanation

This inquiry seeks a program that outputs the maximum positive subsequence from a given array. A subsequence, in this context, refers to a series of numbers in the array that are not necessarily contiguous but are derived from the array by omitting certain elements without rearranging the remaining ones. The maximum positive subsequence is defined as the subsequence with the largest sum that consists solely of positive integers. To tackle this problem, consider the following important points: Since the goal is to identify the subsequence rather than merely calculating the sum, we must determine both the starting and ending indices of this subsequence. The array may include various types of numbers, including negative values. To handle this, we can apply Kadane's algorithm, which is effective for identifying the maximum subarray sum. However, we will need to make slight modifications to cater specifically to the requirement of finding the maximum positive subsequence.

Suggested Answer

Here is a Python program that implements the modified Kadane's algorithm: def max_subsequence(arr): max_sum = 0 current_sum = 0 start = 0 end = 0 for i in range(len(arr)): current_sum += arr[i] if current_sum max_sum: max_sum = current_sum end = i return arr[start:end + 1] This program functions by traversing the array and continuously adding the elements to the current_sum variable. If the current_sum falls below zero at any point, it is reset to zero, and the start pointer is moved to the next index. When the current_sum surpasses the max_sum, the max_sum is updated to the current_sum, and the end pointer is adjusted to the current index. This method allows it to keep track of the largest positive subsequence within the array.

Alternative Answer

This is how you might implement the program in Java: public class Main { public static void maxSubSequence(int[] a) { int maxSum = 0; int currSum = 0; int start = 0; int end = 0; for (int i = 0; i maxSum) { maxSum = currSum; end = i; } } for (int i = start; i This Java program executes a similar function to the Python version, traversing the array while keeping track of both the current sum and the maximum sum. If the current sum drops below 0, it gets reset, and if it surpasses the maximum sum, the maximum sum is updated. This process continues throughout the entire array, yielding the indices that correspond to the maximum positive subsequence.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.