
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 sum subarray with at-least k numbers in C++
Let's see the steps to complete the program.
- Initialise the array.
- Initialise max_sum array of size n.
- Find the max sum for every index and store it in max_sum array.
- Compute the sum of all the elements and store it in a variable sum.
- Write a loop that iterates from i = k to n.
- Add a[i] - a[i - k] to the sum.
- Update the result with max of result, sum.
- Update the result with max of result, sum + max_sum[i - k].
Example
Let's see the code.
#include<bits/stdc++.h> using namespace std; int getMaxSum(int a[], int n, int k) { int maxSum[n]; maxSum[0] = a[0]; int currentMax = a[0]; for (int i = 1; i < n; i++) { currentMax = max(a[i], currentMax+a[i]); maxSum[i] = currentMax; } int sum = 0; for (int i = 0; i < k; i++) { sum += a[i]; } int result = sum; for (int i = k; i < n; i++) { sum += a[i] - a[i-k]; result = max(result, sum); result = max(result, sum + maxSum[i-k]); } return result; } int main() { int a[] = {5, 3, 7, -5, 6, 2, 1}; int k = 6; cout << getMaxSum(a, 7, k) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
19
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
- Related Questions & Answers
- Shortest Subarray with Sum at Least K in C++
- Subarray sum with at least two elements in JavaScript
- Largest subarray having sum greater than k in C++
- Maximum sum subsequence with at-least k distant elements in C++
- Maximum sum subsequence with at-least k distant elements in C++ program
- Largest Sum Contiguous Subarray
- Subarray Sum Equals K in C++
- Longest Substring with At Least K Repeating Characters in C++
- C/C++ Program for Largest Sum Contiguous Subarray?
- Find subarray with given sum - (Nonnegative Numbers) in C++
- Maximum Size Subarray Sum Equals k in C++
- Find subarray with given sum - (Handles Negative Numbers) in C++
- Program to find largest average of sublist whose size at least k in Python
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Largest permutation after at most k swaps in C++
Advertisements