[0, 2, 1, 0, 0, 0, 0, 2, 0, 0, 0]
[-1, 2, -1, -1, 0, -1, -1, 2, -1, -1, 0]
[0, 1, 0] => [-1, 1, -1]
[0, 2, 0, 0, 0] => [-1, 2, -1, -1, 0]
[2, 1, 0, 0, 0] => [2, -1, -1, 0, 0]
[2, 0, 1, 0, 0] => [2, -1, 1, -1, 0]
function transformArray(sourceArray) {
const arr = sourceArray.slice(0);
for (let max = Math.max(...arr); max > 0; max--) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === max) {
const startRange = Math.max(0, i - max);
const endRange = Math.min(arr.length - 1, i + max);
for (let i2 = startRange; i2 <= endRange; i2++) {
if (arr[i2] >= max) continue;
if (startRange > Math.max(0, i2 - arr[i2])) continue;
if (endRange < Math.min(arr.length - 1, i2 + arr[i2])) continue;
arr[i2] = -1;
}
}
}
}
return arr;
}
function process (source) {
const result = source.slice(0);
const count = result.length;
result.forEach((n, i) => {
if (n > 0) {
const min = Math.max(i - n, 0);
const max = Math.min(i + n, count - 1);
for (let c = min; c <= max; c++) {
let check = result[c];
if (check < 1 || (check < n && c - check >= min && c + check <= max)) {
result[c] = -1;
}
}
}
});
return result;
}
function processDirection(arr, first, end, step) {
let top = -1;
for (let i = first; i !== end; i += step) {
const value = arr[i];
if (value <= top) {
arr[i] = -1;
} else {
top = value;
}
top--;
}
}
function updateArray(arr) {
processDirection(arr, 0, arr.length, 1);
processDirection(arr, arr.length - 1, -1, -1);
return arr;
}
// --------
updateArray([5, 1, 1, 0, 2, 1, 1, 0]); // [5, -1, -1, -1, 2, -1, 1, -1]