Similar Problems
Similar Problems not available
Minimum Difference In Sums After Removal Of Elements - Leetcode Solution
Companies:
LeetCode: Minimum Difference In Sums After Removal Of Elements Leetcode Solution
Difficulty: Hard
Topics: dynamic-programming heap-priority-queue array
Problem statement:
Given an array of integers nums, split it into two non-empty subarrays left and right, such that:
- The absolute difference between the sums of left and right subarrays is as small as possible.
- Return the minimum possible difference between the sums of the two subarrays after splitting the array.
Example 1:
Input: nums = [1,2,3,4,5] Output: 1 Explanation: We can split the array into [1,2,4] and [3,5], and the absolute difference between their sums is minimal.
Example 2:
Input: nums = [6,2,3,4,5,1] Output: 1 Explanation: We can split the array into [6,2,4] and [3,5,1], and the absolute difference between their sums is minimal.
Example 3:
Input: nums = [1,2,3,4,6] Output: 1 Explanation: We can split the array into [1,2,4] and [3,6], and the absolute difference between their sums is minimal.
Solution:
To solve the minimum difference in sums after removal of elements problem, we can use dynamic programming. We can create a 2D array dp, where dp[i][j] represents the minimum possible difference between the sums of two subarrays in the range [0, i] using j elements from the left subarray.
Initially, we can fill the first row and column of the dp array. dp[i][0] represents the sum of all elements in the range [0, i], and dp[0][j] represents the jth element in the array.
Next, we can iterate through the remaining cells of the dp array. For each cell dp[i][j], we can either include the (i+1)th element in the left subarray or exclude it. If we include it, we can update the dp value as follows:
dp[i][j] = min(dp[i][j], abs(dp[i-1][j-1] - nums[i]))
If we exclude the (i+1)th element, we can update the dp value as follows:
dp[i][j] = min(dp[i][j], dp[i-1][j])
After filling the dp array, we can return dp[n-1][m], where n is the length of the nums array and m is n/2.
Time Complexity:
The time complexity of the above solution is O(n^2), where n is the length of the nums array.
Space Complexity:
The space complexity of the above solution is also O(n^2), where n is the length of the nums array.
Code:
class Solution:
def minimumDifference(self, nums: List[int]) -> int:
n = len(nums)
m = n//2
dp = [[float('inf')]*(m+1) for _ in range(n)]
tot = nums[0]
dp[0][0] = 0
for i in range(1, n):
tot += nums[i]
dp[i][0] = tot
for i in range(1, n):
for j in range(1, m+1):
if j > i:
break
dp[i][j] = min(dp[i][j], abs(dp[i-1][j-1] - nums[i]))
dp[i][j] = min(dp[i][j], dp[i-1][j])
return dp[n-1][m]
Minimum Difference In Sums After Removal Of Elements Solution Code
1