|
| 1 | +/** |
| 2 | + * Two pointers - sliding window technique - 01 |
| 3 | + * ============================================ |
| 4 | + * |
| 5 | + * This technique is used to find subarrays or substrings given a set of |
| 6 | + * conditions. |
| 7 | + * |
| 8 | + * Refer: |
| 9 | + * |
| 10 | + * https://www.geeksforgeeks.org/window-sliding-technique/ |
| 11 | + * https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems |
| 12 | + */ |
| 13 | + |
| 14 | +#include "tests.h" |
| 15 | + |
| 16 | +/* =========================================================================== |
| 17 | + * Algorithms implementation |
| 18 | + * =========================================================================== |
| 19 | + */ |
| 20 | + |
| 21 | +/* TC : O(n) |
| 22 | + * SC : O(1) |
| 23 | + */ |
| 24 | +#define _2p_sw_maxSumKConseq_desc \ |
| 25 | + "Two Pointers - Sliding Window - " \ |
| 26 | + "Maximum sum of K consequent elements" |
| 27 | + |
| 28 | +int maxSumKConseq(const vi_t &a, int k) |
| 29 | +{ |
| 30 | + int n = size(a); |
| 31 | + int r = 0, c = 0; |
| 32 | + fii (i, k) r += a[i]; |
| 33 | + c = r; |
| 34 | + for (int i = k; i < n; i++) { |
| 35 | + c += a[i] - a[i - k]; |
| 36 | + r = max(r, c); |
| 37 | + } |
| 38 | + return r; |
| 39 | +} |
| 40 | + |
| 41 | +/* =========================================================================== |
| 42 | + * Test code |
| 43 | + * =========================================================================== |
| 44 | + */ |
| 45 | +#define _2p_sw_maxSumKConseq_check(i, k, e) \ |
| 46 | + { \ |
| 47 | + int a = maxSumKConseq(i, k); \ |
| 48 | + CHECK_EQ(e, a); \ |
| 49 | + string im = format("array = {}, k = {}", to_string(i), k); \ |
| 50 | + SET_CUSTOM_SUCCESS_MSG(im, to_string(a)); \ |
| 51 | + SHOW_OUTPUT(i, a); \ |
| 52 | + } |
| 53 | + |
| 54 | +TEST(maxSumKConseq, _2p_sw_maxSumKConseq_desc) |
| 55 | +{ |
| 56 | + vi2_t _a{ |
| 57 | + {100, 200, 300, 400}, |
| 58 | + {1, 4, 2, 10, 23, 3, 1, 0, 20}, |
| 59 | + }; |
| 60 | + vi_t _k{2, 4}; |
| 61 | + vi_t _e{700, 39}; |
| 62 | + int n = size(_a); |
| 63 | + fii (i, n) _2p_sw_maxSumKConseq_check(_a[i], _k[i], _e[i]); |
| 64 | +} |
| 65 | + |
| 66 | +INIT_TEST_MAIN(); |
0 commit comments