Jobs
Interviews

Solve Maximum Sub Array of Non-Negative Numbers using JavaScript Language

Solve Maximum Sub Array of Non-Negative Numbers using JavaScript to enhance your skills with javascript coding practice , master coding concepts, and prepare for interviews with practical exercises and detailed solutions.

Maximum Sub Array of Non-Negative Numbers

Difficulty : Medium

Categories :

  • Arrays
  • Dynamic programming

Find the maximum sub-array consisting of only non-negative numbers from an array. The sub-array must be contiguous.

Rules for determining the maximum sub-array:

  • Primary criteria: Maximum sum of elements
  • If sums are equal: Choose the sub-array with maximum length
  • If lengths are also equal: Choose the sub-array with minimum starting index
  • If no valid sub-array exists: Return [-1]

Constraints:

  • 1 ≤ array.length ≤ 105
  • -105 ≤ array[i] ≤ 105

Examples:

Input: arr = [1,2,5,-7,2,3]
Output: [1,2,5]
Explanation: [1,2,5] has sum=8 which is greater than [2,3] with sum=5
Input: arr = [-1,2]
Output: [2]
Explanation: Only positive sub-array is [2]
Input: arr = [1,2,3]
Output: [1,2,3]
Explanation: All elements are non-negative

Follow-up:

Can you solve it with O(n) time complexity and O(1) space complexity?

Problem Solving

Input

What You'll Find Here

Hands-On Exercises Work on coding problems inspired by real-world scenarios.

Detailed Explanations Break down complex solutions into easy-to-understand steps.

Interactive Learning Test your skills in an engaging and fun way.

Choose from the following categories