Similar Problems

Similar Problems not available

Minimum Sum Of Squared Difference - Leetcode Solution

Companies:

LeetCode:  Minimum Sum Of Squared Difference Leetcode Solution

Difficulty: Medium

Topics: math sorting heap-priority-queue array  

The Minimum Sum Of Squared Difference problem on LeetCode is a problem that involves finding the minimum possible sum of the squared differences between two arrays, given that one of the arrays can be rearranged in any order.

The problem can be solved using dynamic programming, where we keep track of the minimum sum of squared differences at each step. This can be done by iterating through each element in the array that can be rearranged and updating the minimum sum for each possible position.

To solve this problem, we can first sort both arrays in non-decreasing order. Then, we can define a two-dimensional array dp of size n x k, where n is the length of the arrays and k is the number of distinct elements in the first array.

The dp[i][j] represents the minimum sum of squared differences between the first i elements of the sorted array (that can be rearranged) and the last n-i elements of the second sorted array, with the j-th element of the first array being the largest element considered so far. We initialize dp[i][j] to be infinity for all i and j.

Next, we can define a helper function cost(i, j) that calculates the sum of squared differences between the i-th element of the first array and the j-th element of the second array. This can be done by computing (A[i] - B[j])^2, where A and B are the sorted arrays.

Then, we can iterate through each element in the first array that can be rearranged and update dp accordingly. For each i, we compute the minimum cost for each j from 1 to k, and update dp[i][j] to be the minimum of dp[i-1][j-1] + cost(i-1, j-1) and dp[i][j-1], since we can either choose to use the i-th element of the first array at the j-th position or not.

Finally, the answer is the minimum value in the last row of dp.

Here is the Python code that implements the above algorithm:

def minSumOfSquares(self, nums1: List[int], nums2: List[int]) -> int:
    n1, n2 = len(nums1), len(nums2)
    k = len(set(nums1))
    A, B = sorted(nums1), sorted(nums2)
    dp = [[float('inf')] * k for _ in range(n1 + 1)]
    dp[0][0] = 0
    
    def cost(i, j):
        return (A[i] - B[j]) ** 2
    
    for i in range(1, n1 + 1):
        for j in range(1, k + 1):
            for l in range(j):
                dp[i][j-1] = min(dp[i][j-1], dp[i-1][l] + cost(i-1, j-1))
                
    return dp[n1][k-1]

The time complexity of this algorithm is O(n^2k), where n is the length of the arrays and k is the number of distinct elements in the first array. The space complexity is also O(nk).

Minimum Sum Of Squared Difference Solution Code

1