How to check whether the array has a continuous subarray in C++

  C & C ++ Interview Q&A

Today we will read on this article – Continuous Saber Sum in C ++. If we have a list of non-negative numbers and the target integer k, then we need to write a function to check whether the array has at least a constant size of 2 s and it goes up to several k, n * k Up to sums where n is also an integer. So if the input is like [23,2,4,6,7], and k = 6, the result will be correct, since [2,4] is a constant prefix of size 2 and a sum of up to 6.

Example

#include <bits/stdc++.h>
using namespace std;
class program {
   public:
   bool checkSubarraySum(vector<int>& nums, int k) {
      unordered_map<int, int> m;
      m[0] = -1;
      int sum = 0;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         sum += nums[i];
         if(k)
         sum %= k;
         if(m.count(sum) && i - m[sum] >= 2){
            return true;
         }
         if(!m.count(sum)) m[sum] = i;
      }
      return false;
   }
};
main(){
   vector<int> v = {23,2,4,6,7};
   Solution ob;
   cout << (ob.checkSubarraySum(v, 6));
}

Input

[23,2,4,6,7]
6

Output

1

LEAVE A COMMENT