Swapping Pairs Make Sum Equal || Program 56 || Competitive Coding || Learning Monkey ||

Опубликовано: 30 Сентябрь 2024
на канале: Learning Monkey
716
11

Swapping Pairs Make Sum Equal
In this class, We discuss Swapping Pairs Make Sum Equal.
Readers can prepare an entire competitive coding course to crack product development companies. Click Here.
The reader should have basic coding skills to work with competitive coding. Click here.
Question:
Given two arrays of size N and M.
Our task is to find a pair of elements from each array.
Swapping the elements makes the sum of elements in both arrays is same.
Example:
N = 6, M = 4
A = [4, 1, 2, 1, 1, 2]
B = [3, 6, 3, 3]
Output = 1
Swap elements one from A and three from B.
After swapping, the sum of elements is the same in both arrays.
There is a possibility to swap, so output 1.
If there is no such possibility, Then output -1.
Logic:
Two ways we can solve this example.
1) Using sorting
2) Using Heap
Both ways are important to understand.
The step-by-step explanation is provided in the video.
Code:
class Solution:
def findSwapValues(self,a, n, b, m):
sum1,sum2=0,0
for i in range(n):
sum1+=a[i]
for j in range(m):
sum2+=b[j]

a.sort()
b.sort()

i,j=0,0
while(iltn and jltm):
val=sum1-(a[i])+(b[j])
val2=sum2+(a[i])-(b[j])
if val==val2:
return 1
if(valgtval2):
i+=1
else:
j+=1
return -1

a=[4, 1, 2, 1, 1, 2]
b = [3, 6, 3, 3]
ob=Solution()
z=ob.findSwapValues(a,6,b,4)
print(z)

class Solution:
def findSwapValues(self,a, n, b, m):
x, y = {}, {}

s1, s2 = 0, 0
for i in range(n):
s1 += a[i]
x[a[i]] = x.get(a[i], 0) + 1
for i in range(m):
s2 += b[i]
y[b[i]] = y.get(b[i], 0) + 1

if (s1 - s2) % 2:
return -1

for p in x:
q = ((s2 - s1)//2) + p
if q in y:
return 1
return -1

a=[4, 1, 2, 1, 1, 2]
b = [3, 6, 3, 3]
ob=Solution()
z=ob.findSwapValues(a,6,b,4)
print(z)
Link for playlists:
   / @learningmonkey  


Link for our website: https://learningmonkey.in

Follow us on Facebook @   / learningmonkey  

Follow us on Instagram @   / learningmonkey1  

Follow us on Twitter @   / _learningmonkey  

Mail us @ [email protected]