Created
April 21, 2025 19:30
-
-
Save tatsuyax25/049f5732132e2282ca293d34d0400644 to your computer and use it in GitHub Desktop.
You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences
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
/** | |
* This function calculates the number of valid arrays that can be reconstructed | |
* from a given list of differences within a specified range. | |
* | |
* @param {number[]} differences - An array of differences between consecutive elements. | |
* @param {number} lower - The lower bound of the valid range. | |
* @param {number} upper - The upper bound of the valid range. | |
* @return {number} - The number of valid arrays that can be reconstructed. | |
*/ | |
var numberOfArrays = function(differences, lower, upper) { | |
// Initialize the lower and upper bounds of the array values | |
let low = lower, high = upper; | |
// Iterate through the differences array in reverse order | |
for (let i = differences.length - 1; i >= 0; i--) { | |
// Adjust the current bounds by subtracting the current difference | |
low = low - differences[i]; | |
high = high - differences[i]; | |
// Check if the adjusted bounds are completely out of the valid range | |
if ((low < lower && high < lower) || (low > upper && high > upper)) { | |
return 0; // No valid array can be formed | |
} | |
// Clamp the bounds to the valid range | |
low = Math.max(low, lower); | |
high = Math.min(high, upper); | |
} | |
// Return the number of possible values for the first element in the valid range | |
return (high - low) + 1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment