
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest Subarray Having Sum Greater Than K in C++
In this tutorial, we are going to write a program that finds the largest subarray have sum greater than k.
Let's see the steps to solve the problem.
- Initialise the array.
- Iterate over the array and store sum at each index in a vector along with the index.
- Sort the above sums based on sum and index.
- Initialise an array to store the indexes.
- Write a loop that iterates till n.
- Update the values with min index of above indexes array and previous sums array index.
- Initialise sum to 0.
- Write a loop that iterates till n.
- Add current element to sum.
- If the sum is greater than k.
- The maximum subarray length is i + 1.
- Else the maximum subarray length is
- Find the index from the previous sums using binary search.
- The sum that is less than sum - k - 1 is the element index we want.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; bool compare(const pair<int, int>& a, const pair<int, int>& b) { if (a.first == b.first) { return a.second < b.second; } return a.first < b.first; } int findIndex(vector<pair<int, int> >& previousSums, int n, int val) { int start = 0; int end = n - 1; int mid, result = -1; while (start <= end) { mid = (start + end) / 2; if (previousSums[mid].first <= val) { result = mid; start = mid + 1; }else { end = mid - 1; } } return result; } int getLargestSubArray(int arr[], int n, int k) { int maxLength = 0; vector<pair<int, int> > previousSums; int sum = 0, minIndexes[n]; for (int i = 0; i < n; i++) { sum = sum + arr[i]; previousSums.push_back({ sum, i }); } sort(previousSums.begin(), previousSums.end(), compare); minIndexes[0] = previousSums[0].second; for (int i = 1; i < n; i++) { minIndexes[i] = min(minIndexes[i - 1], previousSums[i].second); } sum = 0; for (int i = 0; i < n; i++) { sum = sum + arr[i]; if (sum > k) { maxLength = i + 1; }else { int ind = findIndex(previousSums, n, sum - k - 1); if (ind != -1 && minIndexes[ind] < i) { maxLength = max(maxLength, i - minIndexes[ind]); } } } return maxLength; } int main() { int arr[] = { 5, 3, -3, 2, 4, 7 }; int k = 5, n = 6; cout << getLargestSubArray(arr, n, k) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
6
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements