Fork me on GitHub

Max Size Subarray Sum Equals k

Description

https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/

Brutal Force O(n^3)

Prefix Sum: O(n^2)

Naive Hash Table: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int ret = 0;
int sum = 0;
int size = nums.size();
if (size == 0) return 0;
unordered_map<int, vector<int>> mapping; ///Mapping the sum to [0,..index]
vector<int> dp(size + 1, -1);
for (int i = 0; i < size; ++i) {
dp[i] = sum;
sum += nums[i];
mapping[dp[i]].push_back(i);
}
dp[size] = sum;
sum += nums[size];
mapping[dp[size]].push_back(size);

for (int j = 0; j < size + 1; ++j) {
if (mapping.count(dp[j] - k)) {
for (auto& item : mapping[dp[j] - k])
ret = max(ret, j - item);
}
}

return ret;
}
};

Hash Table: O(n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
int ret = 0;
int sum = 0;
int size = nums.size();
if (size == 0) return 0;
unordered_map<int, int> mapping; ///Mapping the sum to [0,..index]
vector<int> dp(size + 1, -1);
dp[0] = 0;
mapping[0] = 0;
for (int i = 1; i <= size; ++i) {
sum += nums[i - 1];
dp[i] = sum;
if (mapping.count(dp[i]) == 0) mapping[dp[i]] = i;
}

for (int j = 0; j < size + 1; ++j) {
if (mapping.count(dp[j] - k)) {
ret = max(ret, j - mapping[dp[j] - k]);
}
}

return ret;
}
};