Advertisement
Vennox

Untitled

Dec 13th, 2023
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. function minOperations(price, query) {
  2. const n = price.length;
  3. const sortedPrices = [...price].sort((a, b) => a - b);
  4.  
  5. const calculateOperations = (median) => {
  6. let totalOperations = 0;
  7. for (let i = 0; i < n; i++) {
  8. totalOperations += Math.abs(price[i] - median);
  9. }
  10. return totalOperations;
  11. };
  12.  
  13. const result = [];
  14. for (let i = 0; i < query.length; i++) {
  15. const median = n % 2 === 0 ? Math.floor((sortedPrices[n / 2 - 1] + sortedPrices[n / 2]) / 2) : sortedPrices[Math.floor(n / 2)];
  16. const operations = calculateOperations(query[i]);
  17. result.push(operations);
  18. }
  19.  
  20. return result;
  21. }
  22.  
  23. // Example usage:
  24. const prices = [1, 2, 3];
  25. const queries = [3, 2, 1, 5];
  26.  
  27. const operations = minOperations(prices, queries);
  28. console.log("Minimum operations for each query:", operations);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement