To solve this problem, we need to find the longest subarray (a contiguous segment of the array) whose sum is at least ( p ). Given the constraints ( n \leq 100,000 ), an efficient approach is required to handle large inputs effectively.
Approach:
-
Binary Search on Subarray Length:
- We can perform a binary search on the possible lengths of the subarray, ranging from 1 to ( n ).
- For each mid-value in the binary search, we check if there exists a subarray of that length with a sum of at least ( p ).
-
Prefix Sums for Efficient Sum Calculation:
- To efficiently calculate the sum of any subarray, we use prefix sums. A prefix sum array allows us to compute the sum of elements between any two indices in constant time.
-
Checking Subarray Sums:
- For a given length ( k ), iterate through the array to check if any subarray of length ( k ) has a sum ( \geq p ).
- If such a subarray exists, update the answer and try to find a longer subarray by adjusting the binary search range. Otherwise, reduce the search range.
-
Edge Cases:
- If no valid subarray is found, return
-1.
Implementation:
The implementation involves reading input from a file, computing prefix sums, performing binary search, and writing the result to an output file.
Here is the C++ code that accomplishes this:
#include <bits/stdc++.h>
using namespace std;
int main(){
// Open input and output files
freopen("MAXSEQ.INP","r",stdin);
freopen("MAXSEQ.OUT","w",stdout);
int n;
long long p;
cin >> n >> p;
vector<long long> a(n);
for(int i=0;i<n;i++) cin >> a[i];
// Compute prefix sums
vector<long long> prefix(n+1,0);
for(int i=1;i<=n;i++) prefix[i] = prefix[i-1] + a[i-1];
// Binary search for the maximum k
int left=1, right=n, ans=-1;
while(left <= right){
int mid = left + (right-left)/2;
bool found=false;
for(int i=mid;i<=n;i++){
if(prefix[i] - prefix[i-mid] >= p){
found=true;
break;
}
}
if(found){
ans=mid;
left = mid +1;
}
else{
right=mid -1;
}
}
cout<<ans;
}
Explanation:
-
File Handling:
- The program reads input from
MAXSEQ.INP and writes the result to MAXSEQ.OUT.
-
Prefix Sum Calculation:
- The
prefix array is constructed such that prefix[i] contains the sum of the first i elements of the array.
-
Binary Search:
- We perform a binary search to find the maximum length ( k ) where at least one subarray of length ( k ) has a sum ( \geq p ).
- For each mid-value, we slide a window of size ( k ) across the array and check the sum using the prefix sums.
-
Output:
- The final answer
ans is printed. If no valid subarray is found, ans remains -1.
Example:
-
Input 1:
5 6
-2
3
2
-2
3
Output 1:
4
-
Input 2:
4 9
2
3
2
-2
Output 2:
-1
This solution efficiently handles large inputs within the given constraints and correctly identifies the longest subarray satisfying the required condition.