RainX_69

PARTITION ARRAY INTO K SUBARRAYS TO MAXIMIZE BEAUTY | INFOSYS POWER PROGRAMMER OA

Feb 28th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | Source Code | 0 0
  1. Given N array of an elements of array A. You should partition it into exactly non empty sub arrays such that each element belongs to exactly one subarrays. The beauty of the subarray equals X*X where X is the maximum element in the subarray. For example, the beauty of the subarray [2,4,3] equals 4*4=16.
  2.  
  3. Output the maximum sum of beauties you can achieve, by partitioning the array A into exactly K subarrays.
  4.  
  5. Example 1-
  6. N=1
  7. K=1
  8. A=[1,1,1]
  9. Output - 1
  10. Explanation - Because we are only having one subarray that is the array itself where max element is 1.
  11.  
  12. Example 2-
  13. N=3
  14. K=2
  15. A=[1,2,3]
  16. Output - 13
  17. Explanation - Partition it like [1,2],[3] => 2*2 + 3*3=13  
  18.  
  19. Constraints-
  20. 1<=N<=10^5
  21. 1<=K<=min(10,N)
  22. 1<=A[i]<=10^6
  23.  
  24. ------------------------------------------------------------------------------------------------------------------------------------
  25.  
  26. vector<vector<long long>> dp;
  27. vector<int> G;
  28.  
  29. long long helper(vector<int> &arr, int curr, int k){
  30.     if(k==1){
  31.         return (long long)G[curr]*G[curr];
  32.     }
  33.     if(dp[curr][k]!=-1){
  34.         return dp[curr][k];
  35.     }
  36.     long long res=INT_MIN;
  37.     long long mx=INT_MIN;
  38.     for(int i=curr;i<=arr.size()-k;i++){
  39.         mx=max(mx,(long long)arr[i]);
  40.         long long beauty=helper(arr,i+1,k-1);
  41.         if(beauty!=INT_MIN){
  42.             beauty+=(long long)(mx*mx);
  43.             res=max(res,beauty);
  44.         }
  45.     }
  46.     return dp[curr][k]=res;    
  47. }
  48.  
  49. int GetMaxBeauty(int N, int K, vector<int>& arr){
  50.     G=arr;
  51.     for(int i=N-2;i>=0;i--){
  52.         G[i]=max(G[i],G[i+1]);
  53.     }
  54.     dp.resize(N+1,vector<long long>(K+1,-1));
  55.     return helper(arr,0,K);
  56. }  // TLE (10/11) PASSED
  57.  
  58.  
  59. ---------------------------------------------------------------------------------------------------------------------------------------
  60.  
  61. JUST PICK K LARGEST ELEMENTS, CUZ WE CAN ALWAYS PARTITION SUCH THAT THESE K ELEMENTS END UP IN K PARTITIONS
  62.  
  63. int GetMaxBeauty(int N, int K, vector<int>& arr){
  64.     priority_queue<int,vector<int>,greater<int>> pq;
  65.     for(int i=0;i<N;i++){
  66.         pq.push(arr[i]);
  67.         if(pq.size()>K){
  68.             pq.pop();
  69.         }
  70.     }
  71.     int res=0;
  72.     while(!pq.empty()){
  73.         res+=(pq.top()*pq.top());
  74.         pq.pop();
  75.     }
  76.     return res;
  77. }  // ACCEPTED
  78.  
  79.  
Advertisement
Add Comment
Please, Sign In to add comment