Created
June 9, 2022 10:11
-
-
Save HarshKumarChoudary/d0ddc221ffd4c18e0fba1f6ab7fccdf3 to your computer and use it in GitHub Desktop.
There are two parallel roads, each containing N and M buckets, respectively. Each bucket may contain some balls. The balls in first road are given in an array a and balls in the second road in an array b. The buckets on both roads are kept in such a way that they are sorted according to the number of balls in them. Geek starts from the end of th…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Geek collects the balls :- | |
// https://practice.geeksforgeeks.org/problems/geek-collects-the-balls5515/1/?page=1&status[]=unsolved&curated[]=7&sortBy=submissions# | |
class Solution{ | |
public: | |
int maxBalls(int n, int m, vector<int> a, vector<int> b){ | |
int i=0,j=0; | |
int s1=0,s2=0; | |
sort(a.begin(),a.end()); | |
sort(b.begin(),b.end()); | |
while(i<n || j<m){ | |
if(i<n && j<m){ | |
if(a[i]<b[j]){ | |
s1 += a[i]; | |
i++; | |
} | |
else if(a[i]>b[j]){ | |
s2 += b[j]; | |
j++; | |
} | |
else { | |
int x = a[i]; | |
int c1 = 0,c2 = 0; | |
while(a[i++]==x)c1++; | |
while(b[j++]==x)c2++; | |
i--,j--; | |
if(s1>s2){ | |
s2 = s1 + (c1+c2-1)*x; | |
if(c1>1)s1 += (c1+c2-2)*x; | |
else s1 += x; | |
} | |
else{ | |
s1 = s2 + (c1 + c2 -1)*x; | |
if(c2>1)s2 += (c1+c2-2)*x; | |
else s2 += x; | |
} | |
} | |
} | |
else if(i<n){ | |
s1 += a[i]; | |
i++; | |
} | |
else if(j<m){ | |
s2 += b[j]; | |
j++; | |
} | |
} | |
return max(s1,s2); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment