Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function minOperations(price, query) {
- const n = price.length;
- const sortedPrices = [...price].sort((a, b) => a - b);
- const calculateOperations = (median) => {
- let totalOperations = 0;
- for (let i = 0; i < n; i++) {
- totalOperations += Math.abs(price[i] - median);
- }
- return totalOperations;
- };
- const result = [];
- for (let i = 0; i < query.length; i++) {
- const median = n % 2 === 0 ? Math.floor((sortedPrices[n / 2 - 1] + sortedPrices[n / 2]) / 2) : sortedPrices[Math.floor(n / 2)];
- const operations = calculateOperations(query[i]);
- result.push(operations);
- }
- return result;
- }
- // Example usage:
- const prices = [1, 2, 3];
- const queries = [3, 2, 1, 5];
- const operations = minOperations(prices, queries);
- console.log("Minimum operations for each query:", operations);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement