FastPrepFastPrep
Problem Brief

Min Operations to Adjust Prices

INTERNOA

The manager of the Amazon warehouse has decided to make changes to the inventory by changing the prices of the products. Currently, the inventory has n products, where the price of the i-th product is represented by the array element prices[i].

The manager is given two integers:

  • k - which is the maximum amount by which a product's price can be adjusted (increased or decreased) in a single operation, and
  • d - which represents the target price difference.
  • The goal is to ensure that the difference between the highest and lowest prices in the inventory is strictly less than d.

    In order to make changes to the inventory, the manager can do the following operation any number of times:

  • The manager selects two indices x, y (1 ≤ x, yn), and an integer p (1 ≤ pk).
  • The manager increases the price of the product x by p.
  • The manager decreases the price of the product y by p.
  • Given n products, an array prices, and the two integers k and d, find the minimum number of operations that the manager has to perform such that the maximum difference between the prices of any two products from the array of products is strictly less than d.

    Function Description

    Complete the function minOperations in the editor.

    minOperations has the following parameters:

    • int prices[n]: an array of integers representing the prices of n products
    • int k: the maximum amount that a price can be increased or decreased by in one operation
    • int d: the target difference

    Returns

    int: the minimum number of operations required to ensure the condition is satisfied, i.e., the difference between the maximum and minimum prices of the array of products is strictly less than d.

    1Example 1

    Input
    prices = [1, 5, 9, 11], k = 4, d = 2
    Output
    3
    Explanation
    Example 1 illustration
    The manager needs to perform a total of 3 operations. It is not possible to achieve the required condition, where the difference between the highest and lowest prices is strictly less than d = 2, in fewer than 3 operations. Therefore, the result is 3.

    2Example 2

    Input
    prices = [1, 4, 6], k = 1, d = 2
    Output
    2
    Explanation
    Example 2 illustration
    Here, we have 3 products with prices [1, 4, 6]. The manager can adjust prices with a maximum of k = 1 per operation, and the required maximum price difference is d = 2. Now the max difference is 4 - 3 = 1, which is strictly less than d = 2. Hence, the manager needs to perform 2 operations.

    Constraints

    Limits and guarantees your solution can rely on.

    • 1 ≤ n ≤ 10^3
    • 1 ≤ prices[i] ≤ 10^3
    • 1 ≤ k ≤ 10^3
    • 1 ≤ d ≤ 10^3
    public int minOperations(int[] prices, int k, int d) {
      // write your code here
    }
    
    Input

    prices

    [1, 5, 9, 11]

    k

    4

    d

    2

    Output

    3

    Sign in to submit your solution.