0

The question is asking, if all the subarray of length k have equal sum, if not can it be achieved by inserting elements. If it can be then print the new array else print -1. There is no limit to no. of elements you can insert, but it should be less than n.

Constraints

(1≤t≤50)
(1≤k≤n≤100)
(1≤a(i)≤n)

code

#include <bits/stdc++.h>
using namespace std;

int main(){
   int t;
   cin>>t;
   int n,k;
   while(t--){
   bool find = true;
   cin >> n>>k;
   vector<int> a(n);
   int ar[n+1]={0};
   for(int i=0;i<n;i++){
       cin>>a[i];
       if(i<k){
           ar[a[i]]=1;
       }
   }
   for(int i=k;i<n;i++){
       if(ar[a[i]]!=1){
           find = false;
           break;
       }
   }
   if(find ==false)
   cout<<-1;
   else{
       for(int i=k;i<a.size();i++){
           if(a[i]!=a[i-k]){
               a.insert(a.begin()+i,a[i-k]);
           }
       }
       cout<<a.size()<<"\n";
       for(int i=0;i<a.size();i++){
           cout<<a[i]<<" ";
       }
   }
   cout<<"\n";
  }
   return 0;
}

I'm new to STL. When i'm trying to submit this code it is showing memory limit exceeded on codeforces.

  • Standard C++ [does not have variable-length arrays](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) (VLAs). Use `std::vector` instead. You already do this for `a`, so why not for `ar` as well? Also, see: [Why should I not `#include `?](https://stackoverflow.com/q/31816095/1458097) And also: [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/q/1452721/1458097) – heap underrun May 25 '22 at 08:19
  • `for(int i=k;i – Igor Tandetnik May 27 '22 at 14:04

0 Answers0