I’m working on the LeetCode problem Partition Array into Two Arrays to Minimize Sum Difference, and I’ve written the following C++ solution:
class Solution {
public:
int minimumDifference(vector<int>& nums) {
int n = nums.size();
int sum = accumulate(nums.begin(), nums.end(), 0);
vector<bool> dp(sum + 1, false);
dp[0] = true;
for (int i = 0; i < n; i++) {
for (int j = sum; j >= nums[i]; j--) {
dp[j] = dp[j] || dp[j - nums[i]];
}
}
int ans = INT_MAX;
for (int i = 0; i <= sum / 2; i++) {
if (dp[i]) {
ans = min(ans, sum - 2 * i);
}
}
return ans;
}
};
However, when testing my solution, I encountered the following error:
Line 13: Char 25:
=
==23==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000148 at pc 0x5555ee612af6 bp 0x7ffcf93492d0 sp 0x7ffcf93492c8
READ of size 8 at 0x502000000148 thread T0
#0 0x5555ee612af5 in operator bool /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/bits/stl_bvector.h:96:17
#1 0x5555ee612af5 in Solution::minimumDifference(std::vector<int, std::allocator<int>>&) solution.cpp:13:25
#2 0x5555ee611b4f in __helper__ solution.cpp:13:28
#3 0x5555ee611b4f in main solution.cpp:13:40
Could someone please help me understand what might be causing this error and how I can fix it? Thank you!
I tried implementing a dynamic programming solution where dp[j] represents whether it’s possible to achieve sum j using elements from the nums array. I expected the solution to correctly compute the minimum difference between two partitions of nums.