Similar Problems
Similar Problems not available
Partition Array Into Two Arrays To Minimize Sum Difference - Leetcode Solution
LeetCode: Partition Array Into Two Arrays To Minimize Sum Difference Leetcode Solution
Difficulty: Hard
Topics: dynamic-programming binary-search two-pointers array bit-manipulation
Problem Statement:
Given an array nums of integers, partition it into two (contiguous) subarrays left and right so that:
- Every element in left is less than or equal to every element in right.
- left and right have non-empty lengths.
- left has the smallest possible size.
Return the length of left after such a partitioning.
Approach:
- Sort the given array in increasing order.
- Initialize an array leftSum[] of size n+1, and a variable totalSum = 0.
- Traverse the sorted array and add the element to totalSum.
- For each index i from 1 to n-1, calculate the leftSum[i] as the sum of the first i elements of the sorted array.
- Initialize variables minDiff and leftSize to infinity.
- Traverse the array from left to right.
- For each index i from 1 to n-1, calculate the difference between the sum of the first i elements and the sum of the remaining elements (totalSum - leftSum[i]).
- If the difference is less than or equal to minDiff, update minDiff and leftSize to the current values.
- Return leftSize.
Code:
class Solution {
public:
int partitionDisjoint(vector<int>& nums) {
int n = nums.size();
vector<int> sortedNums(nums);
sort(sortedNums.begin(), sortedNums.end());
vector<int> leftSum(n+1, 0);
int totalSum = 0;
for(int i=0; i<n; i++) totalSum += nums[i];
for(int i=1; i<n; i++) leftSum[i] = leftSum[i-1] + sortedNums[i-1];
int minDiff = INT_MAX, leftSize = INT_MAX;
for(int i=1; i<n; i++){
int diff = totalSum - leftSum[i];
if(diff <= minDiff){
minDiff = diff;
leftSize = i;
}
}
return leftSize;
}
};
Time Complexity: O(n log n) - due to sorting the array.
Space Complexity: O(n) - used for the leftSum array.
Partition Array Into Two Arrays To Minimize Sum Difference Solution Code
1