给定一个由N 个正整数组成的数组A[] ,任务是找到最大可能的值:
F(M) = M % A[0] + M % A[1] + …. + M % A[N -1] where M can be any integer value
例子:
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.
方法:
请按照以下步骤解决问题:
- 计算所有数组元素的 LCM。
- 如果M等于阵列的LCM,则F(M)= 0即F(M)的最小可能值。这是因为,对于每个第i个索引, M % a[i]将始终为 0。
- 对于 M = 阵列元素的 LCM – 1, F(M)被最大化。这是因为,对于每个第i个索引, M % a[i]等于a[i] – 1 ,这是可能的最大值。
- 因此, F(M)的最大可能值可以是数组元素的总和– N。
下面是上述方法的实现:
C++
// C++ program to find the
// maximum sum of modulus
// with every array element
#include
using namespace std;
// Function to return the
// maximum sum of modulus
// with every array element
int maxModulosum(int a[], int n)
{
int sum = 0;
// Sum of array elements
for (int i = 0; i < n; i++) {
sum += a[i];
}
// Return the answer
return sum - n;
}
// Driver Program
int main()
{
int a[] = { 3, 4, 6 };
int n = sizeof(a) / sizeof(a[0]);
cout << maxModulosum(a, n);
return 0;
}
Java
// Java program to find the maximum
// sum of modulus with every array
// element
import java.io.*;
class GFG{
// Function to return the maximum
// sum of modulus with every array
// element
static int maxModulosum(int a[], int n)
{
int sum = 0;
// Sum of array elements
for(int i = 0; i < n; i++)
{
sum += a[i];
}
// Return the answer
return sum - n;
}
// Driver Code
public static void main (String[] args)
{
int a[] = new int[]{ 3, 4, 6 };
int n = a.length;
System.out.println(maxModulosum(a, n));
}
}
// This code is contributed by Shubham Prakash
Python3
# Python3 program to find the
# maximum sum of modulus
# with every array element
# Function to return the
# maximum sum of modulus
# with every array element
def maxModulosum(a, n):
sum1 = 0;
# Sum of array elements
for i in range(0, n):
sum1 += a[i];
# Return the answer
return sum1 - n;
# Driver Code
a = [ 3, 4, 6 ];
n = len(a);
print(maxModulosum(a, n));
# This code is contributed by Code_Mech
C#
// C# program to find the maximum
// sum of modulus with every array
// element
using System;
class GFG{
// Function to return the maximum
// sum of modulus with every array
// element
static int maxModulosum(int []a, int n)
{
int sum = 0;
// Sum of array elements
for(int i = 0; i < n; i++)
{
sum += a[i];
}
// Return the answer
return sum - n;
}
// Driver Code
public static void Main(String[] args)
{
int []a = new int[]{ 3, 4, 6 };
int n = a.Length;
Console.Write(maxModulosum(a, n));
}
}
// This code is contributed
// by shivanisinghss2110
Javascript
输出:
10
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live