function castleBuilder(heights) {
if (heights.length < 2) {
// not enough blocks to build a castle
return 0;
}
let castleCount = 1; // start with 1 castle for the first block
let direction = ""; // direction of the current slope
let slopeStart = 0; // index of the start of the current slope
for (let i = 1; i < heights.length; i++) {
if (heights[i] > heights[i - 1]) {
// going up
if (direction === "down") {
// end of a valley
castleCount++;
}
direction = "up";
} else if (heights[i] < heights[i - 1]) {
// going down
if (direction === "up" || direction === "") {
// end of a hill
castleCount++;
}
direction = "down";
}
// else, flat land, do nothing
// update the start of the current slope
if (direction === "up" || direction === "down" || i === heights.length - 1) {
slopeStart = i;
}
}
return castleCount;
}
// Test case:
const land0 = [3, -1, -5, -5, 2, 4, 7, 5, 1, 1, 1, 4];
console.log(castleBuilder(land0)); // Output: 5
// Test case 1: flat land
const land1 = [1, 1, 1, 1, 1];
console.log(castleBuilder(land1)); // Output: 0 (no hills or valleys)
// Test case 2: complete hill and valley
const land2 = [1, 2, 3, 4, 3, 2, 1];
console.log(castleBuilder(land2)); // Output: 2 (one hill and one valley)
// Test case 3: incomplete hill and valley at the beginning and end
const land3 = [3, 2, 3, 1, 2, 3, 4];
console.log(castleBuilder(land3)); // Output: 2 (one hill and one valley)
// Test case 4: multiple hills and valleys
const land4 = [3, -1, -5, -5, 2, 4, 7, 5, 1, 1, 1, 4];
console.log(castleBuilder(land4)); // Output: 6 (three hills and three valleys)
// Test case 5: two-block land
const land5 = [1, 2];
console.log(castleBuilder(land5)); // Output: 1 (one hill)
// Test case 6: one-block land
const land6 = [1];
console.log(castleBuilder(land6)); // Output: 0 (not enough blocks to build a castle)