39uint64_t
subarray_sum(int64_t sum,
const std::vector<int64_t> &in_arr) {
40 int64_t nelement = in_arr.size();
41 int64_t count_of_subset = 0;
42 int64_t current_sum = 0;
43 std::unordered_map<int64_t, int64_t>
47 for (int64_t i = 0; i < nelement; i++) {
48 current_sum += in_arr[i];
50 if (current_sum == sum) {
54 if (sumarray.find(current_sum - sum) != sumarray.end()) {
55 count_of_subset += (sumarray[current_sum - sum]);
57 sumarray[current_sum]++;
59 return count_of_subset;
70 std::cout <<
"1st test ";
71 std::vector<int64_t> array1 = {-7, -3, -2, 5, 8};
73 backtracking::subarray_sum::subarray_sum(0, array1) ==
76 std::cout <<
"passed" << std::endl;
79 std::cout <<
"2nd test ";
80 std::vector<int64_t> array2 = {1, 2, 3, 3};
81 assert(backtracking::subarray_sum::subarray_sum(6, array2) ==
84 std::cout <<
"passed" << std::endl;
87 std::cout <<
"3rd test ";
88 std::vector<int64_t> array3 = {1, 1, 1, 1};
89 assert(backtracking::subarray_sum::subarray_sum(1, array3) ==
92 std::cout <<
"passed" << std::endl;
95 std::cout <<
"4th test ";
96 std::vector<int64_t> array4 = {3, 3, 3, 3};
97 assert(backtracking::subarray_sum::subarray_sum(6, array4) ==
100 std::cout <<
"passed" << std::endl;
103 std::cout <<
"5th test ";
104 std::vector<int64_t> array5 = {};
105 assert(backtracking::subarray_sum::subarray_sum(6, array5) ==
108 std::cout <<
"passed" << std::endl;