TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
subarray_sum.cpp
Go to the documentation of this file.
1
16#include <cassert>
17#include <cstdint>
18#include <iostream>
19#include <unordered_map>
20#include <vector>
21
26namespace backtracking {
32namespace subarray_sum {
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>
44 sumarray; // to store the subarrays count
45 // frequency having some sum value
46
47 for (int64_t i = 0; i < nelement; i++) {
48 current_sum += in_arr[i];
49
50 if (current_sum == sum) {
51 count_of_subset++;
52 }
53 // If in case current_sum is greater than the required sum
54 if (sumarray.find(current_sum - sum) != sumarray.end()) {
55 count_of_subset += (sumarray[current_sum - sum]);
56 }
57 sumarray[current_sum]++;
58 }
59 return count_of_subset;
60}
61} // namespace subarray_sum
62} // namespace backtracking
63
68static void test() {
69 // 1st test
70 std::cout << "1st test ";
71 std::vector<int64_t> array1 = {-7, -3, -2, 5, 8}; // input array
72 assert(
73 backtracking::subarray_sum::subarray_sum(0, array1) ==
74 1); // first argument in subarray_sum function is the required sum and
75 // second is the input array, answer is the subarray {(-3,-2,5)}
76 std::cout << "passed" << std::endl;
77
78 // 2nd test
79 std::cout << "2nd test ";
80 std::vector<int64_t> array2 = {1, 2, 3, 3};
81 assert(backtracking::subarray_sum::subarray_sum(6, array2) ==
82 2); // here we are expecting 2 subsets which sum up to 6 i.e.
83 // {(1,2,3),(3,3)}
84 std::cout << "passed" << std::endl;
85
86 // 3rd test
87 std::cout << "3rd test ";
88 std::vector<int64_t> array3 = {1, 1, 1, 1};
89 assert(backtracking::subarray_sum::subarray_sum(1, array3) ==
90 4); // here we are expecting 4 subsets which sum up to 1 i.e.
91 // {(1),(1),(1),(1)}
92 std::cout << "passed" << std::endl;
93
94 // 4rd test
95 std::cout << "4th test ";
96 std::vector<int64_t> array4 = {3, 3, 3, 3};
97 assert(backtracking::subarray_sum::subarray_sum(6, array4) ==
98 3); // here we are expecting 3 subsets which sum up to 6 i.e.
99 // {(3,3),(3,3),(3,3)}
100 std::cout << "passed" << std::endl;
101
102 // 5th test
103 std::cout << "5th test ";
104 std::vector<int64_t> array5 = {};
105 assert(backtracking::subarray_sum::subarray_sum(6, array5) ==
106 0); // here we are expecting 0 subsets which sum up to 6 i.e. we
107 // cannot select anything from an empty array
108 std::cout << "passed" << std::endl;
109}
110
115int main() {
116 test(); // run self-test implementations
117 return 0;
118}
for vector container
Functions for the Subset sum implementation.
static void test()
Self-test implementations.
int main()
Main function.