leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1590.cpp (639B)


      1 class Solution {
      2   public:
      3     int minSubarray(const vector<int> &nums, int p) const {
      4         const int n = size(nums);
      5 
      6         int target = 0;
      7         for (const int n : nums)
      8             target = (target + n) % p; // avoid overflow
      9         if (target == 0) return 0;
     10 
     11         unordered_map<int, int> um;
     12         int res = n, crnt = 0;
     13         um[0] = -1;
     14 
     15         for (int i = 0; i < n; i++) {
     16             crnt = (crnt + nums[i]) % p;
     17 
     18             const int goal = (crnt - target + p) % p;
     19             if (um.count(goal)) res = min(res, i - um[goal]);
     20 
     21             um[crnt] = i;
     22         }
     23 
     24         return res == n ? -1 : res;
     25     }
     26 };