Last active
December 13, 2023 18:47
-
-
Save avegancafe/13c3ed9a72ac191d96dfea720aa71bb9 to your computer and use it in GitHub Desktop.
This file contains 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
function solution(arr: number[]) { | |
const longestSubarrays: number[] = [] | |
let lastElement: number | null = null | |
let lastDirection: 'up' | 'down' | null = null | |
let currentChainLength: number = 0 | |
function sum(x: number, agg: number = 0) { | |
if (x == 1) { | |
return agg + 1 | |
} | |
return sum(x - 1, agg + x) | |
} | |
for (let x of arr) { | |
if (lastElement == null) { | |
lastElement = x | |
continue | |
} | |
if (x > lastElement) { | |
if (lastDirection == 'down') { | |
const i = Math.max(longestSubarrays.length - 1, 0) | |
currentChainLength += 1 | |
longestSubarrays[i] = sum(currentChainLength) | |
} | |
if (lastDirection == null || lastDirection == 'up') { | |
currentChainLength = 1 | |
longestSubarrays[longestSubarrays.length] = 1 | |
} | |
lastDirection = 'up' | |
} | |
if (x < lastElement) { | |
if (lastDirection == 'up') { | |
const i = Math.max(longestSubarrays.length - 1, 0) | |
currentChainLength += 1 | |
longestSubarrays[i] = sum(currentChainLength) | |
} | |
if (lastDirection == null || lastDirection == 'down') { | |
currentChainLength = 1 | |
longestSubarrays[longestSubarrays.length] = 1 | |
} | |
lastDirection = 'down' | |
} | |
if (x == lastElement) { | |
currentChainLength = 0 | |
lastDirection = null | |
} | |
lastElement = x | |
} | |
return longestSubarrays.reduce((agg, x) => agg + x, 0) | |
} | |
console.log(solution([9, 8, 7, 6, 5])) // 4 | |
console.log(solution([2, 3, 7])) // 2 | |
console.log(solution([10, 10, 10])) // 0 | |
console.log(solution([1, 2, 1, 2, 1])) // 10 | |
console.log( | |
solution([944846388, 993352669, 473719581, 896064794, 646066085, 7272438041]) | |
) // 15 | |
// [1, 2, 1, 2] // 7 | |
// [1, 2, 1] // 3 | |
// [1, 2] // 1 | |
// | |
// 1: 1 | |
// 2: 3 // i + (i * i - 1) | |
// 3: 7 // i + 4 | |
// 4: 10 // i + 6 | |
// 5: 15 // i + 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment