Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a 0-indexed integer array nums consisting of 3 * n elements.
You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:
n elements belonging to the first part and their sum is sumfirst.n elements belonging to the second part and their sum is sumsecond.The difference in sums of the two parts is denoted as sumfirst - sumsecond.
sumfirst = 3 and sumsecond = 2, their difference is 1.sumfirst = 2 and sumsecond = 3, their difference is -1.Return the minimum difference possible between the sums of the two parts after the removal of n elements.
Example 1:
Input: nums = [3,1,2] Output: -1 Explanation: Here, nums has 3 elements, so n = 1. Thus we have to remove 1 element from nums and divide the array into two equal parts. - If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1. - If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1. - If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2. The minimum difference between sums of the two parts is min(-1,1,2) = -1.
Example 2:
Input: nums = [7,9,5,8,1,3] Output: 1 Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each. If we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12. To obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1. It can be shown that it is not possible to obtain a difference smaller than 1.
Constraints:
nums.length == 3 * n1 <= n <= 1051 <= nums[i] <= 105Problem summary: You are given a 0-indexed integer array nums consisting of 3 * n elements. You are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts: The first n elements belonging to the first part and their sum is sumfirst. The next n elements belonging to the second part and their sum is sumsecond. The difference in sums of the two parts is denoted as sumfirst - sumsecond. For example, if sumfirst = 3 and sumsecond = 2, their difference is 1. Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1. Return the minimum difference possible between the sums of the two parts after the removal of n elements.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[3,1,2]
[7,9,5,8,1,3]
product-of-array-except-self)find-subsequence-of-length-k-with-the-largest-sum)find-minimum-cost-to-remove-array-elements)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2163: Minimum Difference in Sums After Removal of Elements
class Solution {
public long minimumDifference(int[] nums) {
int m = nums.length;
int n = m / 3;
long s = 0;
long[] pre = new long[m + 1];
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
for (int i = 1; i <= n * 2; ++i) {
int x = nums[i - 1];
s += x;
pq.offer(x);
if (pq.size() > n) {
s -= pq.poll();
}
pre[i] = s;
}
s = 0;
long[] suf = new long[m + 1];
pq = new PriorityQueue<>();
for (int i = m; i > n; --i) {
int x = nums[i - 1];
s += x;
pq.offer(x);
if (pq.size() > n) {
s -= pq.poll();
}
suf[i] = s;
}
long ans = 1L << 60;
for (int i = n; i <= n * 2; ++i) {
ans = Math.min(ans, pre[i] - suf[i + 1]);
}
return ans;
}
}
// Accepted solution for LeetCode #2163: Minimum Difference in Sums After Removal of Elements
func minimumDifference(nums []int) int64 {
m := len(nums)
n := m / 3
s := 0
pre := make([]int, m+1)
q1 := hp{}
for i := 1; i <= n*2; i++ {
x := nums[i-1]
s += x
heap.Push(&q1, -x)
if q1.Len() > n {
s -= -heap.Pop(&q1).(int)
}
pre[i] = s
}
s = 0
suf := make([]int, m+1)
q2 := hp{}
for i := m; i > n; i-- {
x := nums[i-1]
s += x
heap.Push(&q2, x)
if q2.Len() > n {
s -= heap.Pop(&q2).(int)
}
suf[i] = s
}
ans := int64(1e18)
for i := n; i <= n*2; i++ {
ans = min(ans, int64(pre[i]-suf[i+1]))
}
return ans
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
# Accepted solution for LeetCode #2163: Minimum Difference in Sums After Removal of Elements
class Solution:
def minimumDifference(self, nums: List[int]) -> int:
m = len(nums)
n = m // 3
s = 0
pre = [0] * (m + 1)
q1 = []
for i, x in enumerate(nums[: n * 2], 1):
s += x
heappush(q1, -x)
if len(q1) > n:
s -= -heappop(q1)
pre[i] = s
s = 0
suf = [0] * (m + 1)
q2 = []
for i in range(m, n, -1):
x = nums[i - 1]
s += x
heappush(q2, x)
if len(q2) > n:
s -= heappop(q2)
suf[i] = s
return min(pre[i] - suf[i + 1] for i in range(n, n * 2 + 1))
// Accepted solution for LeetCode #2163: Minimum Difference in Sums After Removal of Elements
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn minimum_difference(nums: Vec<i32>) -> i64 {
let m = nums.len();
let n = m / 3;
let mut s = 0i64;
let mut pre = vec![0i64; m + 1];
let mut pq = BinaryHeap::new(); // max-heap
for i in 1..=2 * n {
let x = nums[i - 1] as i64;
s += x;
pq.push(x);
if pq.len() > n {
if let Some(top) = pq.pop() {
s -= top;
}
}
pre[i] = s;
}
s = 0;
let mut suf = vec![0i64; m + 1];
let mut pq = BinaryHeap::new();
for i in (n + 1..=m).rev() {
let x = nums[i - 1] as i64;
s += x;
pq.push(Reverse(x));
if pq.len() > n {
if let Some(Reverse(top)) = pq.pop() {
s -= top;
}
}
suf[i] = s;
}
let mut ans = i64::MAX;
for i in n..=2 * n {
ans = ans.min(pre[i] - suf[i + 1]);
}
ans
}
}
// Accepted solution for LeetCode #2163: Minimum Difference in Sums After Removal of Elements
function minimumDifference(nums: number[]): number {
const m = nums.length;
const n = Math.floor(m / 3);
let s = 0;
const pre: number[] = Array(m + 1);
const q1 = new MaxPriorityQueue<number>();
for (let i = 1; i <= n * 2; ++i) {
const x = nums[i - 1];
s += x;
q1.enqueue(x);
if (q1.size() > n) {
s -= q1.dequeue();
}
pre[i] = s;
}
s = 0;
const suf: number[] = Array(m + 1);
const q2 = new MinPriorityQueue<number>();
for (let i = m; i > n; --i) {
const x = nums[i - 1];
s += x;
q2.enqueue(x);
if (q2.size() > n) {
s -= q2.dequeue();
}
suf[i] = s;
}
let ans = Number.MAX_SAFE_INTEGER;
for (let i = n; i <= n * 2; ++i) {
ans = Math.min(ans, pre[i] - suf[i + 1]);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.