Minimum Difference In Sums After Removal Of Elements

Solution For Minimum Difference In Sums After Removal Of Elements

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]

“`

Step by Step Implementation For Minimum Difference In Sums After Removal Of Elements

Given an array of integers, remove two different elements such that the sum of the resulting array is minimal.

For example, given the array [5,4,2,1], removing the elements 4 and 2 results in an array with a sum of 5, which is the minimal sum possible.

Solution:

public int minDifference(int[] nums) {

int n = nums.length;

if (n <= 2)

return 0;

int sum = 0;

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

sum += nums[i];

int min = sum;

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

for (int j = i + 1; j < n; j++) {

int diff = Math.abs(sum - 2 * (nums[i] + nums[j]));

if (diff < min)

min = diff;

}

}

return min;

}
Given an array of integers, remove exactly one element from the array such that the sum of all remaining elements is minimized. If there are multiple elements with the same value, remove the one with the lowest index.

def removeElement(arr): 

# Base case 
if len(arr) == 1: 
    return arr[0] 

# Sort the array in ascending order 
arr.sort() 

# Initialize two variables for keeping 
# track of sum of two subarrays 
sum1 = 0
sum2 = 0

# Calculate the sum of all array elements 
for i in range(len(arr)): 
    sum2 += arr[i] 

# Initialize min value 
min_diff = abs(sum1 - (sum2 - sum1)) 

# Consider each array element as the 
# right boundary of the left subarray 
# and find the minimum sum difference 
for i in range(len(arr) - 1): 
    sum1 += arr[i] 
    sum2 -= arr[i] 
    diff = abs(sum1 - (sum2 - sum1)) 
    if diff < min_diff: 
        min_diff = diff 

return min_diff
// Given an array of integers, return the minimum difference between the sums of its two non-empty subarrays. 

// Input: nums = [3,1,2,4]
// Output: 1
// Explanation: The minimum difference is between the subarrays [3,1] and [2,4].

// We can remove one element from either subarray to get the result.

// Input: nums = [1,2,3,4,5]
// Output: 2
// Explanation: The minimum difference is between the subarrays [1,2,3] and [4,5].

// We can remove two elements from either subarray to get the result.


// Solution: 

// We can find the minimum difference by iterating through the array and finding the minimum difference between the sums of the two subarrays at each index.

function minDifference(nums) {
    let min = Infinity;
    for (let i = 0; i < nums.length - 1; i++) {
        let left = nums.slice(0, i);
        let right = nums.slice(i + 1);
        let diff = Math.abs(left.reduce((a, b) => a + b, 0) - right.reduce((a, b) => a + b, 0));
        min = Math.min(min, diff);
    }
    return min;
}
class Solution {
public:
    int minimumDifference(vector& nums) {
        // sort the array
        sort(nums.begin(), nums.end());
        
        // initialize minimum difference to be the difference between the first two elements
        int minDiff = nums[1] - nums[0];
        
        // start from the second element in the array
        for (int i = 2; i < nums.size(); i++) {
            // update minimum difference if necessary
            minDiff = min(minDiff, nums[i] - nums[i-1]);
        }
        
        // return the minimum difference
        return minDiff;
    }
};
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two of its elements is less than or equal to limit.

In other words, you want to find the longest subarray of consecutive elements where the absolute difference between any two elements is less than or equal to limit.

If there is no such subarray, return 0.

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9


Scroll to Top

Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]