Skip to content

Instantly share code, notes, and snippets.

@Crackiii
Last active July 14, 2020 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Crackiii/0dc297191841d5fc6271b0275357ecab to your computer and use it in GitHub Desktop.
Save Crackiii/0dc297191841d5fc6271b0275357ecab to your computer and use it in GitHub Desktop.
Longest Sub Array
//O(n^2) way
function maxLength(a, k) {
// Write your code here
var _arr = [];
for (var i = 0; i <= a.length; i++) {
for (var j = i + 1; j <= a.length; j++) {
console.log(j - i, _arr.length && a.slice(i, j).reduce((a, b) => a + b, 0) <= k)
if (j - i > _arr.length && a.slice(i, j).reduce((a, b) => a + b, 0) <= k) {
_arr = a.slice(i, j);
}
}
}
return _arr.length;
}
//Efficient Way
var subarraySum = function(nums, k) {
let count = 0;
let sum = 0;
let hash = {};
for(let i = 0; i < nums.length; i++) {
sum += nums[i];
count += (sum === k) ? 1 : 0;
count += ((sum - k) in hash) ? hash[sum-k] : 0
hash[sum] = (sum in hash) ? hash[sum] + 1 : 1;
}
return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment