In an attempt to find the index of the maximum element after left rotation, I have come up with a method. The idea is to rotate array 'a' based on another array called 'rotate'. Each element in the 'rotate' array determines how many times array 'a' should be rotated. For example, if the element is 2, then array 'a' will be rotated twice. During each iteration, the index of the maximum element in the rotated array is found and stored. However, the code execution is taking too long and the test times out eventually.
const a = [1, 2, 4, 3];
const rotate = [2, 1];
The expected output of getLargestItemIndices
function would be an array like this:
[0, 1]
For the first iteration (2 rotations), the max value (4) is at index 0, and for the second iteration, the max value is at index 1.
let indices = [];
const getMaxValueIndex = (arr) => {
const maxValue = Math.max.apply(Math, arr);
return arr.indexOf(maxValue);
}
const rotateArray = (a, d) => {
while (d) {
a.push(a.shift());
d--;
}
indices.push(getMaxValueIndex(a));
}
function getLargestItemIndices(a, rotate) {
for (let index = 0; index < rotate.length; index++) {
rotateArray(a.slice(), rotate[index]);
}
return indices;
}