Advertisement
STANAANDREY

sub arr of given sum

Mar 15th, 2023
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. pair<int, int> subArrOfGivenSum(const vector<int> &nums, int target) {
  6.     unordered_map<int, int> indexOf;
  7.     indexOf[0] = -1;
  8.     int prefSum = 0;
  9.     for (int i = 0; i < (int)nums.size(); i++) {
  10.         prefSum += nums[i];
  11.         int diff = prefSum - target;
  12.         if (indexOf.count(diff)) {
  13.             return make_pair(indexOf[diff] + 1, i);
  14.         }
  15.         indexOf[prefSum] = i;
  16.     }
  17.     return make_pair(-1, -1);
  18. }
  19.  
  20. int main() {
  21.     vector<int> nums = {1, 1, 5, 2, 1, 3, 10, 2, 1};
  22.     pair<int, int> ans = subArrOfGivenSum(nums, 21);
  23.     cout << ans.first << ' ' << ans.second << endl;
  24.     unordered_map<int, int> mp;
  25.     return 0;
  26. }
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement