Last active
July 14, 2020 03:48
-
-
Save Crackiii/0dc297191841d5fc6271b0275357ecab to your computer and use it in GitHub Desktop.
Longest Sub Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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