📌  相关文章
📜  从数组中最大化可能的模和

📅  最后修改于: 2021-09-06 06:37:13             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,任务是找到∑(M mod arr[i])的最大值,其中arr[i]是任何数组元素,对于非负整数M

例子:

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

  • 由于A MOD B是余当A除以B,那么表达式Σ的最大值(M MOD改编[I])为:
  • 考虑到K = Arr[0] × Arr[1] × ···· × Arr[n – 1] ,那么对于[0, N – 1]范围内的每个i(K mod Arr[i]) = 0
  • 因此,((K − 1) mod Arr[i]) = Arr[i] − 1。因此,对于M = K – 1 ,可以获得最优结果。

下面是上述方法的实现:

C++
// C++ Program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to caluclate maximum modulo
// sum possible from a given array
int MaximumModuloSum(int Arr[], int N)
{
    // Stores the sum
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
        sum += Arr[i] - 1;
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 4, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << MaximumModuloSum(arr, N);
 
    return 0;
}


Java
/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static int MaximumModuloSum(int Arr[], int N)
    {
       
        // Stores the sum
        int sum = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
            sum += Arr[i] - 1;
        }
        return sum;
    }
    public static void main(String[] args)
    {
        int arr[] = { 3, 4, 6 };
        int N = 3;
        System.out.println(MaximumModuloSum(arr, N));
    }
}
 
// This code is contributed by aditya7409.


Python3
# Python 3 Program to implement
# the above approach
 
# Function to caluclate maximum modulo
# sum possible from a given array
def MaximumModuloSum( Arr, N):
 
    # Stores the sum
    sum = 0;
 
    # Traverse the array
    for i in range( N ):
        sum += Arr[i] - 1;
     
    return sum;
 
# Driver Code
if __name__ == "__main__":
   
    arr = [ 3, 4, 6 ];
    N = len(arr)
    print(MaximumModuloSum(arr, N))
 
    # This code is contributed by chitranayal.


C#
// C# program for the above approach
using System;
class GFG
{
 
  public static int MaximumModuloSum(int[] Arr, int N)
  {
 
    // Stores the sum
    int sum = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
      sum += Arr[i] - 1;
    }
    return sum;
  }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 3, 4, 6 };
    int N = 3;
    Console.WriteLine(MaximumModuloSum(arr, N));
  }
}
 
// This code is contributed by susmitakundugoaldanga.


Javascript


输出:
10

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live