Pick maximum sum M elements such that contiguous repetitions do not exceed K in C++

C++Server Side ProgrammingProgramming

In this problem, we are given array arr[] and two integers M and K. our task is to create an Array using elements of the given array. The size of the new array should M and any sub-array of size greater than K cannot have all elements the same. we have to print the maximum sum possible by the created array.

Let’s take an example to understand the problem

Input − arr[] = {1, 2, 4, 5, 7 }, M = 5, K = 2

Explanation − array created that satisfies the condition {7, 7, 5, 7, 7}. Here, no sub-array with size more than 2 can have all elements the same.

To solve this problem, we need to create an array using the element that has the maximum value. But we can’t use the max element more than k time, so after k times, we will have to use the second max element of the array. Insert one-second max value after every k max values in the array and create an array of M length. The final output will be the sum of all elements of this array.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
using namespace std;
long int arraySum(int arr[], int n, int m, int k){
   int max1 = arr[0], max2 = arr[0];
   for (int i = 1; i < n; i++) {
      if (arr[i] > max1) {
         max2 = max1;
         max1 = arr[i];
      }
      else if (arr[i] > max2)
         max2 = arr[i];
   }
   int max2count = m / (k + 1);
   long int sum = max2count * max2 + (m - max2count) * max1;
   return sum;
}
int main() {
   int arr[] = { 1, 3, 6, 7, 4, 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int m = 9, k = 2;
   cout<<"The maximum sum of array created from the given array such that no subarray of size greater    than "<<k<<" will have same elements is ";
   cout<<arraySum(arr, n, m, k);
   return 0;
}

Output

The maximum sum of array created from the given array such that no subarray of size greater than 2 will have same elements is 60
raja
Published on 17-Apr-2020 11:01:45
Advertisements