codekofi
← All problems

Problem 80

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1int solution(const vector<int>& nums, int target) {
2
3 int total = 0;
4
5 for (int x : nums) {
6 total += x;
7 }
8
9 if (target > total || target < -total) {
10 return 0;
11 }
12
13 if ((total + target) % 2 != 0) {
14 return 0;
15 }
16
17 int want = (total + target) / 2;
18
19 vector<int> ways(want + 1, 0);
20 ways[0] = 1;
21
22 for (int x : nums) {
23 for (int sum = want; sum >= x; sum--) {
24 ways[sum] += ways[sum - x];
25 }
26 }
27
28 return ways[want];
29}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.