Problem · Array

Minimum Operations Required (2025 Intern)

Learn this problem
EasyIBMINTERNOA
See IBM hiring insights

Problem statement

A shop in HackerLand contains n items where the price of the jth item is price[j]. In one operation, the price of any one item can be increased or decreased by 1.

Given q queries denoted by the array query[], find the minimum number of operations required to make the price of all items equal to each query[i] (0 ≤ i < q).

Note: All queries are independent of each other, i.e., the original price of items is restored after the completion of each query.

Function

minimumOperationsRequired(price: int[], query: int[]) → int[]

Complete the function minimumOperationsRequired in the editor.

minimumOperationsRequired has the following parameters:

  1. 1. int[] price: an array of integers representing the prices of items
  2. 2. int[] query: an array of integers representing the queries

Returns

int[]: an array of integers where the ith integer is the minimum number of operations required for the ith query

Examples

Example 1

price = [1, 2, 3]query = [3, 2, 1, 5]return = [3, 2, 3, 9]

Consider n = 3, q = 4, price[] = [1, 2, 3], query[] = [3, 2, 1, 5]

  1. query[0] = 3. The number of operations required = [2, 1, 0] to make the price of all elements equal to 3. Total number of operations = 2 + 1 + 0 = 3.
  2. query[1] = 2, operations required = [1, 0, 1] 1 + 0 + 1 = 2
  3. query[2] = 1, operations required = [0, 1, 2] 0 + 1 + 2 = 3
  4. query[3] = 5, operations required = [4, 3, 2] 4 + 3 + 2 = 9

The answer is [3, 2, 3, 9].

Constraints

🍓

More IBM problems

drafts saved locally
public int[] minimumOperationsRequired(int[] price, int[] query) {
  // write your code here
}
price[1, 2, 3]
query[3, 2, 1, 5]
expected[3, 2, 3, 9]
checking account