Dsa
Prefix Sum
Medium
Max Subarray Sum with Constraints
You are given an integer array nums. Your goal is to find the maximum sum of a continuous subarray. However, the subarray must contain at least one element and its sum must not exceed a given limit x. Your task is to implement a function that takes these inputs and outputs the maximum sum or -1 if no such subarray exists.
Input Format:
- The first line contains an integer n (the length of the array).
- The second line contains n space-separated integers (the elements of the array nums).
- The third line contains an integer x (the upper limit of the subarray sum).
Output Format:
- Output a single integer representing the maximum sum of the valid subarray, or -1 if no valid subarray exists.
Example:
Input:
5
1 2 3 4 5
7
Output:
7
Key concepts
prefix_summaximum_subarrayconstraints
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now