Computer >> Computer tutorials >  >> Programming >> C++

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.