Dsa
Prefix Sum
Medium
Maximum Subarray Sum within K
You are given an integer array `nums` and an integer `k`. Your goal is to find the maximum sum of any contiguous subarray with a sum less than or equal to `k`. Write a program to read the input and output the maximum sum.
Input format:
- The first line contains an integer `n`, the number of elements in the array.
- The second line contains `n` space-separated integers representing `nums`.
- The third line contains the integer `k`.
Output format:
- Output the maximum sum of the subarray that is less than or equal to `k`. If no valid subarray exists, output 0.
Example:
Input:
6
2 1 3 4 5 1
7
Output:
7
Key concepts
prefix_summaximum_sum
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