Find maximum sum taking every Kth element in the array in C++


In this problem, we are given an array arr[] and an integer k. Our task is to Find the maximum sum taking every Kth element in the array.

Problem description: We need to find the maximum sum of the elements of the array such that they are k indexes apart. i.e. we need to maximize the sum,

sum = arr[i] + arr[i+k] + arr[i + 2*k] + …. arr[i + p*k], such that (i + p*k) < n

Let’s take an example to understand the problem,

Input

arr[] = {5, 3, −1, 2, 4, −5, 6}, k = 4

Output

9

Explanation

All sums of every kth element is
5 + 4 = 9
3 − 5 = −2
−1 + 6 = 5
2
4
−5
6
The maximum is 9

Solution Approach

A Simple solution to the problem is by using two nested loops, the outer one for each elements of the array and the inner one is used to find the sum of taking every kth element from i. i.e. sum = arr[i] + arr[i + k] + arr[i + 2*k] + … + arr[i + p*k] such that (i + p*k) < n.

And return the maximum sum.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findMaxSumK(int arr[], int n, int K){
   int maxSum = -1000;
   for (int i = 0; i < n; i++) {
      int current_Sum = 0;
      for (int j = i; j < n; j += K)
         current_Sum = current_Sum + arr[j];
         maxSum = max(maxSum, current_Sum);
   }
   return maxSum;
}
int main(){
   int arr[] = {5, 3, -1, 2, 4, -5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   int K = 3;
   cout<<"The maximum sum taking every Kth element in the array is
   "<<findMaxSumK(arr, n, K);
   return (0);
}

Output

The maximum sum taking every Kth element in the array is 13

Program to illustrate the working of a solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findMaxSumK(int arr[], int n, int K) {
   int maxSum = -1000;
   int suffSum[n] = {0};
   for (int i = n - 1; i >= 0; i--) {
      if (i + K < n)
         suffSum[i] = suffSum[i + K] + arr[i];
      else
         suffSum[i] = arr[i];
         maxSum = max(maxSum, suffSum[i]);
   }
   return maxSum;
}
int main(){
   int arr[] = {5, 3, -1, 2, 4, -5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   int K = 3;
   cout<<"The maximum sum taking every Kth element in the array is
   "<<findMaxSumK(arr, n, K);
   return (0);
}

Output

The maximum sum taking every Kth element in the array is 13

Updated on: 12-Mar-2021

145 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements