algorithm - How to compute minimum number of operation required to make all the elements of sequence equal to each other - Stack Overflow

PHOTO EMBED

Fri Apr 29 2022 17:53:14 GMT+0000 (Coordinated Universal Time)

Saved by @GreenMark #javascript

//Number of steps in Hackerearth
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {

    var data = input.split('\n');
    var num = parseInt(data[0],10); 

    var aa = data[1].split(' ').map(function(item) { return parseInt(item, 10);});

var bb = data[2].split(' ').map(function(item) { return parseInt(item, 10);});

   process.stdout.write(f(aa,bb));
   //console.log(f(aa,bb));
   
   // Writing output to STDOUT
 
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here

function f(A, B){
  const n = A.length;
  const m = Math.min(...A);
  let result;
  
  for (let t=m; t>=0; t--){
    result = 0;
    
    for (let i=0; i<n; i++){
      if ((A[i] - t) % B[i] == 0){
        result = result + (A[i] - t) / B[i];
        
      } else {
        result = -1;
        break;
      }
    }
    
    if (result > -1)
      return result.toString();
  }
  
  return result.toString();
}
content_copyCOPY

Problem You are given two arrays and . In each step, you can set if . Determine the minimum number of steps that are required to make all 's equal. Input format First line: Second line: Third line: Output format Print the minimum number of steps that are required to make all 's equal. If it is not possible, then print -1. Constraints Sample input 2 5 6 4 3 Sample output -1 Sample Input 5 5 7 10 5 15 2 2 1 3 5 Sample Output 8 Explanation with Example: Given arrays be – A[] = {5, 7, 10, 5, 15}, B[] = {2, 2, 1, 3, 5} Array A Current Index Minimum of Array A Steps Comments {5, 7, 10, 5, 15} 0 5 0 No operation ! {5, 5, 10, 5, 15} 1 5 1 Array element is subtracted once. 7 – 2 = 5 {5, 5, 9, 5, 15} 2 5 2 Array element is subtracted once. 10 – 1 = 9 {5, 5, 8, 5, 15} 2 5 3 Array element is subtracted once. 9 – 1 = 8 {5, 5, 7, 5, 15} 2 5 4 Array element is subtracted once. 8 – 1 = 7 {5, 5, 6, 5, 15} 2 5 5 Array element is subtracted once. 7 – 1 = 6 {5, 5, 5, 5, 15} 2 5 6 Array element is subtracted once. 6 – 1 = 5 {5, 5, 5, 5, 10} 4 5 7 Array element is subtracted once. 15 – 5 = 10 {5, 5, 5, 5, 5} 4 5 8 Array element is subtracted once. 10 – 5 = 5

https://stackoverflow.com/questions/62702690/how-to-compute-minimum-number-of-operation-required-to-make-all-the-elements-of