📌  相关文章
📜  最大化每个 Array 元素的模数总和

📅  最后修改于: 2021-09-07 05:25:42             🧑  作者: Mango

给定一个由N 个正整数组成的数组A[] ,任务是找到最大可能的值:

例子:

方法:
请按照以下步骤解决问题:

  1. 计算所有数组元素的 LCM。
  2. 如果M等于阵列的LCM,则F(M)= 0F(M)的最小可能值。这是因为,对于每个i索引, M % a[i]将始终为 0。
  3. 对于 M = 阵列元素的 LCM – 1, F(M)被最大化。这是因为,对于每个i索引, M % a[i]等于a[i] – 1 ,这是可能的最大值。
  4. 因此, 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