Maximize the sum of modulus with every Array element
Last Updated :
14 Jan, 2022
Given an array A[] consisting of N positive integers, the task is to find the maximum possible value of:
F(M) = M % A[0] + M % A[1] + …. + M % A[N -1] where M can be any integer value
Examples:
Input: arr[] = {3, 4, 6}
Output: 10
Explanation:
The maximum sum occurs for M = 11.
(11 % 3) + (11 % 4) + (11 % 6) = 2 + 3 + 5 = 10
Input: arr[] = {2, 5, 3}
Output:7
Explanation:
The maximum sum occurs for M = 29.
(29 % 2) + (29 % 5) + (29 % 3) = 1 + 4 + 2 = 7.
Approach:
Follow the steps below to solve the problem:
- Calculate the LCM of all array elements.
- If M is equal to the LCM of the array, then F(M) = 0 i.e. the minimum possible value of the F(M). This is because, M % a[i] will always be 0 for every ith index.
- For M = LCM of array elements – 1, F(M) is maximized. This is because, M % a[i] is equal to a[i] – 1 for every ith index, which is the maximum possible.
- Hence, the maximum possible value of F(M) can be Sum of array elements – N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxModulosum( int a[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += a[i];
}
return sum - n;
}
int main()
{
int a[] = { 3, 4, 6 };
int n = sizeof (a) / sizeof (a[0]);
cout << maxModulosum(a, n);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int maxModulosum( int a[], int n)
{
int sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
sum += a[i];
}
return sum - n;
}
public static void main (String[] args)
{
int a[] = new int []{ 3 , 4 , 6 };
int n = a.length;
System.out.println(maxModulosum(a, n));
}
}
|
Python3
def maxModulosum(a, n):
sum1 = 0 ;
for i in range ( 0 , n):
sum1 + = a[i];
return sum1 - n;
a = [ 3 , 4 , 6 ];
n = len (a);
print (maxModulosum(a, n));
|
C#
using System;
class GFG{
static int maxModulosum( int []a, int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
{
sum += a[i];
}
return sum - n;
}
public static void Main(String[] args)
{
int []a = new int []{ 3, 4, 6 };
int n = a.Length;
Console.Write(maxModulosum(a, n));
}
}
|
Javascript
<script>
function maxModulosum(a, n)
{
let sum = 0;
for (let i = 0; i < n; i++) {
sum += a[i];
}
return sum - n;
}
let a = [ 3, 4, 6 ];
let n = a.length;
document.write(maxModulosum(a, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...