1
var maxDistance = function (colors) {2
// using two pointers from start and end3
// Time complexity O(n)4
// Space complexity O(1)7
const end = colors.length - 1;9
// maximum distance possible is length of arr, so start with two pointer10
// one at the start and one at the end11
const startColor = colors[start];12
const endColor = colors[end];14
// base condition, to check if they are not already equal15
if (startColor !== endColor) {19
// move the forward pointer till we find the differend color20
let forwardPtr = start;21
while (startColor === colors[forwardPtr]) {25
// move the backward pointer till we find the differend color26
let backwardPtr = end;27
while (endColor === colors[backwardPtr]) {31
// Till here, We already know that startColor === endColor32
// hence we did two things,33
// 1. we kept startColor fixed and moved backwardPtr till we find different color34
// 2. similarly, we kept endColor fixed and moved the forwardPtr till we find the different color.35
// we will return the max different out of two now.36
return Math.max(Math.abs(start - backwardPtr), Math.abs(end - forwardPtr));