JSFiddle - React, Tailwind, and code Playground

by Qwerty_Wasd

JavaScript

// set operation object or class - irrelevant for js
let opCellThief = {

  // generate array of bank cells with random values
  // 2  <= N <=  105
  cellsBank: Array.from(
    // generate random N - length iterable object
    { length: Math.floor( Math.random() * 104 ) + 2 },

    // generate in callback random cost of each cell
    function () {
      return Math.floor( Math.random() * 1000 ) + 1;
    }
  ),

  // generate a number - amount cells between thieves
  // 0 <= K < N− 1
  stepCells: Math.floor( Math.random() * ( opCellThief.cellsBank - 2 + 1 ) ),

  // get result O(2n)
  // arguments:
  // cells - bank of cells
  // _step - step between thieves
  getCellsThief : function (_cells, _step) {

    // use Map structure like a couple container "cost -> index"
    let mapCells = new Map();

    // set temp array for max values meet conditions of task
    let max = [ 0, 0 ];

    // fisrt O(n)
    // here we're filtering array cells by conditions task
    // forming Map structure and find first max value
    for ( let i = 0; i < _cells.length; i++ ) {
      if (
        _cells[i + _step + 1] ||
        _cells[_cells.length - i + _step]
      ) {
        
        mapCells.set(_cells[i], i);
        
        if (max[0] < _cells[i]) {
          max[0] = _cells[i];
        }
        
      }
    }

    // second O(n)
    // find second max value by conditions task
    for (let i = 0; i < _cells.length; i++) {
      if (_cells[i] !== max[0] && max[1] < _cells[i] && Math.abs(mapCells.get(max[0]) - (mapCells.get(_cells[i]))) > _step) {
        max[1] = _cells[i];
      }
    }
    
    // returning indexes's
    return `${mapCells.get(max[0])} and ${mapCells.get(max[1])}`;
  },

};






console.clear();
//console.log(opCellThief.getCellsThief(opCellThief.cellsBank, opCellThief.stepCells));
console.log(opCellThief.getCellsThief([128, 662, 237, 27, 101, 957, 871, 812, 647, 597, 4, 295, 797, 325, 556, 150, 70, 805, 272, 803], 2)); // 5 and...