Friday, September 20, 2019

Leetcode 325: Maximum Size Subarray Sum Equals K



Notes:

This question can be a very good interview question due to the follow up. The basic idea is that using a hash table to record the index when one unique sum shows up.

if sum[i to j] = sum[0 to j] - sum[0 to i-1] = k, then we just need to check whether (sum[0 to j] - k) is already observed or not, which is sum[0 to i-1]. Thus, we can run this in O(N).

See the code below:

  1. class Solution {
  2. public:
  3.     int maxSubArrayLen(vector<int> &nums, int k) {
  4.         int res = 0, sum = 0;
  5.         unordered_map<int, int> mp;
  6.         for(int i=0; i<nums.size(); ++i) {
  7.             sum += nums[i];
  8.             if(sum == k) res = max(res, i + 1);
  9.             else if (mp.count(sum-k)) res = max(res, i - mp[sum-k]);
  10.             if(!mp.count(sum)) mp[sum] = i;
  11.         }
  12.         return res;
  13.     }
  14. };

No comments:

Post a Comment