2025-04-07 Daily Challenge
Today I have done leetcode's April LeetCoding Challenge with cpp.
April LeetCoding Challenge 7
Description
Partition Equal Subset Sum
Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.
Example 1:
Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: nums = [1,2,3,5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
Constraints:
1 <= nums.length <= 2001 <= nums[i] <= 100
Solution
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = accumulate(nums.begin(), nums.end(), 0);
if((sum & 1) || nums.empty()) return false;
int target = sum >> 1;
vector<bool> dp(target + 1);
dp[0] = true;
for(auto i : nums) {
for(int j = target; j >= i; --j) {
if(dp[j - i]) dp[j] = true;
}
if(dp[target]) return true;
}
return false;
}
};
// Accepted
// 117/117 cases passed (16 ms)
// Your runtime beats 97.09 % of cpp submissions
// Your memory usage beats 92.1 % of cpp submissions (9.1 MB)