Problem · Array

Count Ordered Combination Sums with Negative Values

Learn this problem
HardPinterest logoPinterestFULLTIMEPHONE SCREEN

Problem statement

Given an array of distinct nonzero integers candidates, an integer target, and a positive integer maxLength, return the number of nonempty ordered sequences of at most maxLength values whose sum is target.

  • You may reuse a candidate any number of times.
  • Two sequences with the same values in different orders count separately.
  • Sequences of different lengths count separately.

Function

countOrderedCombinationSumsWithNegatives(candidates: int[], target: int, maxLength: int) → int

Examples

Example 1

candidates = [1,-1]target = 0maxLength = 2return = 2

The valid nonempty sequences are [1,-1] and [-1,1]. The empty sequence is not counted.

Example 2

candidates = [2,-1]target = 3maxLength = 3return = 3

The valid sequences are the three orderings of [2,2,-1].

Example 3

candidates = [-2,-1]target = -3maxLength = 3return = 3

The valid sequences are [-2,-1], [-1,-2], and [-1,-1,-1].

Constraints

  • 1 <= candidates.length <= 30.
  • -100 <= candidates[i] <= 100 and candidates[i] != 0.
  • All values in candidates are distinct.
  • -1000 <= target <= 1000.
  • 1 <= maxLength <= 20.
  • The correct answer fits a signed 32-bit integer.

More Pinterest problems

drafts saved locally
public int countOrderedCombinationSumsWithNegatives(int[] candidates, int target, int maxLength) {
    // Write your code here.
}
candidates[1,-1]
target0
maxLength2
expected2
checking account