How to optimize memory?


#1

vector Solution::solve(vector &A, vector &B) {

 int n=A.size();
 vector<long long> g;
 
 for(int i=0; i<n; i++){
     int max_ele=A[i];
     g.emplace_back((long long)(max_ele));
     
     for(int j=i+1; j<n; j++){
         max_ele=max(max_ele,A[j]);
          g.emplace_back((long long)(max_ele));
     }
   }
//   for(int i=0; i<g.size(); i++){
//     cout<<g[i]<<" ";
// }
// cout<<endl;

   for(int i=0; i<g.size() ;i++){
       long long  prod=1;
       for(int  j=1; j<=sqrt(g[i]); j++){
           
           if(g[i]%j==0){
               if(g[i]/j==j)
                 prod= (prod*j)%1000000007;
           else
               prod=( prod*g[i])%1000000007;
           
           }
       }
       g[i]=prod%1000000007;
   }
//   for(int i=0; i<g.size(); i++){
//     cout<<g[i]<<" ";
// }
// cout<<endl;

 sort(g.rbegin(),g.rend());
 

vector<int> res;
for(int i=0; i<B.size(); i++){
    res.emplace_back((int)(g[B[i]-1]));
}
return res;

}


#2

i faced the same error, then i used an unordered map to store the greatest elements per sub-arrays along with their frequencies, but after that you might get a TLE lol.