oneby7

2-D Dynamic Programming Knapsack

552. Subset Sum

Medium

You are given an array of positive integers arr and a positive integer target. Return true if some subset of arr adds up to exactly target, and false otherwise.

A subset is any selection of elements from arr. The chosen elements do not have to be next to each other, and each element can be chosen at most once. Two equal values at different positions are different elements, so both can be chosen.

Example 1

Input: arr = [8, 3, 11, 5, 2], target = 10

Output: true

Explanation: Two subsets add up to 10: [8, 2] and [3, 5, 2].

Example 2

Input: arr = [5, 9, 12], target = 8

Output: false

Explanation: The subsets add up to 5, 9, 12, 14, 17, 21 and 26. None of them is 8.

Example 3

Input: arr = [6, 1, 4], target = 11

Output: true

Explanation: Only the whole array works: 6 + 1 + 4 = 11. Every smaller subset adds up to 10 or less.

Check your understanding

Work out the answer for this input before you write any code.

arr = [3, 7], target = 6

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 1 ≤ arr[i] ≤ 104
  • 1 ≤ target ≤ 104

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.