Given an array of integers that can include negative numbers, determine if there is a subset with a sum equal to a given target sum.
Subset Sum Problem with Negative Numbers
- Description: Given an array of integers that can include negative numbers, determine if there is a subset with a sum equal to a given target sum.
- Input: An array of integers
arr[]
and a target sumtarget
. - Output: Return
true
if there is a subset with a sum equal to the target sum; otherwise, returnfalse
. - Example:
- Input:
arr = [-1, 2, 3, 4]
,target = 6
- Output:
true
(Subset[-1, 2, 3, 4]
has a sum of 6)
- Input:
Solution:
Subset Sum Problem with Negative Numbers
javapublic class SubsetSumWithNegatives {
public static boolean isSubsetSum(int[] arr, int target) {
int sum = Arrays.stream(arr).sum();
if (target > sum || (sum + target) % 2 != 0) return false;
target = (sum + target) / 2;
boolean[] dp = new boolean[target + 1];
dp[0] = true;
for (int num : arr) {
for (int j = target; j >= num; j--) {
dp[j] = dp[j] || dp[j - num];
}
}
return dp[target];
}
public static void main(String[] args) {
int[] arr = {-1, 2, 3, 4};
int target = 6;
System.out.println(isSubsetSum(arr, target)); // Output: true
}
}
Comments
Post a Comment