Posts Minimize the sum of product (geeksforgeeks - SDE Sheet)
Post
Cancel

Minimize the sum of product (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

You are given two arrays, A and B, of equal size N. The task is to find the minimum value of A[0] * B[0] + A[1] * B[1] + .... + A[N-1] * B[N-1], where shuffling of elements of arrays A and B is allowed.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {

    public long minValue(long a[], long b[], long n)
    {

        Arrays.sort(a);
        Arrays.sort(b);

        long res = 0;

        for(int i=0; i<n; i++){

            long x = a[i];
            long y = b[(int)(n - i - 1)];

            res += (x*y);

        }

        return res;

    }

}
This post is licensed under CC BY 4.0 by the author.