Leetcode 3149. Find the Minimum Cost Array Permutation
You are given two integer arrays of the same length A
and B
. Your task is to permute array A
such that the sum of the product of corresponding elements of A
and B
is minimized.
To clarify, given:
A
and B
of length n
P
of A
that minimizes the sum Σ(A'[i] * B[i])
for i
from 0
to n-1
, where A'
is the permuted version of A
as per permutation P
.Before jumping into the solution, let’s clarify and confirm understanding of the problem:
A
and B
? (e.g., positive/negative, upper/lower limits).A
and B
? (Is it up to 10^5
or more?)A'
?A
and B
guaranteed to be unique?For this example, let’s assume:
A
and B
are integers within the range [-10^4, 10^4]
.A
and B
is up to 10^5
.A
and B
.To minimize the sum Σ(A'[i] * B[i])
, the intuition is to pair the smallest numbers from A
with the largest numbers from B
and vice versa. This works due to the fact that multiplying a large magnitude number with a small magnitude number will yield a smaller product compared to multiplying two large magnitude numbers.
Steps:
A
.B
in descending order.A
and sorted B
.Let’s implement this strategy in Java:
import java.util.Arrays;
public class MinimumCostArrayPermutation {
public static int minCostPermutation(int[] A, int[] B) {
// Sort array A in ascending order
Arrays.sort(A);
// Sort array B in descending order
Arrays.sort(B);
for (int i = 0; i < B.length / 2; i++) {
int temp = B[i];
B[i] = B[B.length - 1 - i];
B[B.length - 1 - i] = temp;
}
// Calculate the minimized sum product
int minSum = 0;
for (int i = 0; i < A.length; i++) {
minSum += A[i] * B[i];
}
return minSum;
}
public static void main(String[] args) {
int[] A = {1, 3, 5};
int[] B = {2, 4, 6};
System.out.println(minCostPermutation(A, B)); // Expected output: 32
}
}
A
takes (O(n \log n)).B
takes (O(n \log n)).B
to descending order takes (O(n)).Hence, the total time complexity is: [ O(n \log n) ]
This is efficient for arrays with lengths up to (10^5).
This solution effectively minimizes the sum of product of corresponding elements from arrays A
and B
by leveraging sorting techniques, ensuring a time complexity of (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?