VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-sum-of-quotients-after-performing-the-given-operation/

⇱ Minimum sum of Quotients after performing the given operation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum sum of Quotients after performing the given operation

Last Updated : 23 Jul, 2025

Given an array A[] of length N, we can change the value of exactly one element of the array to any integer greater than 0, such that the sum of quotients of all the elements when divided by the new element is minimum. In other words, we have to find: , where 0 <= i <= N-1 and k is the index of the element whose value we have changed.

Note: The new element should perfectly divide all the elements of the array, without leaving any remainder.

Examples:

Input: N = 3, A[] = {2, 3, 4}
Output: 4
Explanation: We will alter the element A[1] = 3 to A[1] = 2, then A[] = {2, 2, 4}. Now, the sum of quotients will be:
(A[0] / A[1]) + (A[1] / A[1]) + (A[2] / A[1]) = 1 + 1 + 2 = 4

Input: N = 3, A[] = {8, 8, 8}
Output: 3
Explanation: We can alter A[0] = 8 to A[0] = 8. Now, the sum of quotients will be:
(A[0] / A[0]) + (A[1] / A[0]) + (A[2] / A[0]) = 1 + 1 + 1 = 3

Approach: The problem can be solved using the following approach:

The problem is related to Number Theory and can be solved using calculating the GCD of all the elements of array A[] and using the prefix[], suffix[] arrays to store GCD of prefix and suffix subarrays.

Steps were taken to solve the problem:

  • Create a variable let's say sum to store the sum of all elements.
  • Create prefix and suffix arrays of length N let say pref[] and suff[] respectively.
  • Run a loop and calculate the sum of all elements and store it into sum.
  • If length of A[] is 1, then return 1.
  • Create a variable ans to store the minimum number of operations required.
  • Initialize pref[0] and suff[N-1] = 0
  • Run a loop for i = 1 and i < N and initialize pref[i] = gcd(pref[i-1], A[i-1])
  • Run a loop for i = N-2 and i >=0 and initialize suff[i] = gcd(suff[i+1], A[i+1])
  • Run a loop for i = 0 to i < N:
    • Calculate gcd of pref[i-1] and suff[i+1] and store it in g
    • val = (sum-A[i])/g
    • If (val < ans), then ans = val
  • return ans+1

Code to implement the approach:


Output
4

Time Complexity: O(N*log(max)), where max is the largest element of array A[].
Auxiliary Space: O(N)

Comment