712211. Check if there exists a subsequence with sum K
Check if there exists a subsequence with sum K
Slug: check-if-there-exists-a-subsequence-with-sum-k
Difficulty: Medium
Id: 712211
Topic Tags: None
Company Tags: None
Summary
Given an array of integers, we need to find out whether there exists a subsequence in the given array with sum equal to K. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
Detailed Explanation
The problem involves finding a subsequence in the given array whose sum equals K. We will use a dynamic programming approach for this solution. Let's initialize an array dp of size K + 1, where dp[i] represents whether there exists a subsequence with sum equal to i.
Here are the steps:
- Initialize
dp[0] = true, since an empty subsequence has a sum of 0. - Iterate over the given array. For each element, update the
dparray as follows:- If the current element is greater than K, then we don't need to consider it in our subsequence, so
dp[i + arr[i]] = dp[i]for alli <= K - arr[i]. - Otherwise, update
dp[i + arr[i]] = true, since we have found a new way to reach sumi + arr[i].
- If the current element is greater than K, then we don't need to consider it in our subsequence, so
At the end of this process, check if dp[K] is true. If it is, then there exists a subsequence with sum K. Otherwise, return false.
Time complexity: O(n), where n is the size of the given array. Space complexity: O(K), since we are using an array of size K + 1 to store our dynamic programming table.
Optimized Solutions
Java
public boolean checkSubsequenceSum(int[] arr, int K) {
boolean[] dp = new boolean[K + 1];
dp[0] = true;
for (int i : arr) {
if (i > K) {
for (int j = 0; j <= K - i; j++) {
dp[j + i] = dp[j];
}
} else {
dp[i] = true;
}
}
return dp[K];
}