Target sum

Dynamic Programming DP on subsequences Hard
  • This programming problem is fundamentally a problem about dynamic programming and subset sum, both of which have wide applications in real-world scenarios
  • One practical application of this problem that has been used in the software industry is in the development of financial or budgeting software
  • For instance, these systems may need to calculate the number of possible ways to achieve a particular financial target, using different combinations of expenses or revenues which are represented by the '+'' or '-' signs
  • The modulo operation is also frequently used in cryptographic algorithms which are a critical part of secure communication in software applications

Given an array nums of n integers and an integer target, build an expression using the integers from nums where each integer can be prefixed with either a '+' or '-' sign. The goal is to achieve the target sum by evaluating all possible combinations of these signs. Determine the number of ways to achieve the target sum and return your answer with modulo 109+7.

Examples:

Input: nums = [1, 2, 7, 1, 5], target = 4

Output: 2

Explanation: There are 2 ways to assign symbols to make the sum of nums be target 4.

-1 + 2 + 7 - 1 + 5 = 4

+1 - 2 + 7 - 1 + 5 = 4

Input: nums = [1], target = 1

Output: 1

Explanation: There is only one way to assign symbols to make the sum of nums be target 1.

Input: nums = [2, 1, 3, 1, 2], target = 2

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ nums[i] ≤ 1000
  • 0 <= sum(A[i]) <= 104
  • -1000 <= target <= 1000

Hints

  • "We define the sum of all elements in nums as S. We need to partition the array into two subsets S1 and S2, where S1−S2=target. the problem reduces to counting the number of subsets whose sum is S1. "
  • We define dp[j] as the number of ways to achieve sum j. the recurrence relation is:dp[j]=(dp[j]+dp[j−nums[i]])mod(10^9+7)

Company Tags

Bungie Bloomberg Chewy Epic Systems Siemens Healthineers Etsy Morgan Stanley DoorDash Snowflake Flipkart IBM Visa Unity Technologies Zomato Western Digital Riot Games Optum Medtronic Square Rakuten Target PayPal Activision Blizzard ARM GE Healthcare Google Microsoft Amazon Meta Apple Netflix Adobe