Skip to content

Instantly share code, notes, and snippets.

@emmsdan
Created February 6, 2022 17:59
Show Gist options
  • Save emmsdan/362575cbf6b8bdbc61f0ccd29b3e5810 to your computer and use it in GitHub Desktop.
Save emmsdan/362575cbf6b8bdbc61f0ccd29b3e5810 to your computer and use it in GitHub Desktop.
// 1. Given an array arr and a number N, find a pair (x,y) such that x+y=N. Return null if it doesn’t exist.
// 2. Find the sum of continuous subarray within a one-dimensional array of numbers that has the largest sum.
// 1....
function isPairInArray(arr, n) {
for (let i=0;i < arr.length; i++) {
for (let j=1; j < arr.length; j++) {
if (arr[i] + arr[j] === n && i !== j) {
return [arr[i], arr[j]]
}
}
}
return null;
}
// 1....
function sumOfContinuousSubarray(arr)
{
let max = -Infinity
let maxEnd = 0
for (let sub of arr)
{
maxEnd = maxEnd + sub;
if (max < maxEnd){
max = maxEnd
}
if (maxEnd < 0){
maxEnd = 0
}
}
return max
}
// use this to test your cases
function testCases(result, expected) {
if (JSON.stringify(result) === JSON.stringify(expected)) {
console.log({ result, expected}, 'PASSED')
return
}
console.log({ result, expected}, 'FAILED')
}
// Test cases For
/**
1. Given an array arr and a number N, find a pair (x,y) such that x+y=N. Return null if it doesn’t exist.
**/
let arr = [1, 8, 30, 40, 100, 20];
let n = 60;
let n1 = 70;
let n2 = 140;
// SHOULD pass [40,20]
testCases(isPairInArray(arr, n), [40,20])
// SHOULD pass [30,40]
testCases(isPairInArray(arr, n1), [30,40])
// SHOULD pass [40,100]
testCases(isPairInArray(arr, n2), [40, 100])
/**
2. Find the sum of continuous subarray within a one-dimensional array of numbers that has the largest sum.
**/
const a = [ -2, -1, 1, -1, -2, 1, 5, -3 ]
const b = [ -2, -3, 4, -1, -2, 1, 5, -3 ]
const c = [ -2, -3, 4, -6, -2, 1, 9, -3 ]
// SHOULD pass 6
testCases(sumOfContinuousSubarray(a), 6)
// SHOULD pass 7
testCases(sumOfContinuousSubarray(b), 7)
// SHOULD pass 10
testCases(sumOfContinuousSubarray(c), 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment