Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize the sum of Array by formed by adding pair of elements
Next article icon

Maximize the sum of modulus with every Array element

Last Updated : 14 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 
 

  1. Calculate the LCM of all array elements.
  2. 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.
  3. 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.
  4. Hence, the maximum possible value of F(M) can be Sum of array elements - N.


Below is the implementation of the above approach: 
 

C++
// C++ program to find the // maximum sum of modulus // with every array element #include <bits/stdc++.h> 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
<script>      // Javascript program to find the      // maximum sum of modulus      // with every array element           // Function to return the      // maximum sum of modulus      // with every array element      function maxModulosum(a, n)      {          let sum = 0;           // Sum of array elements          for (let i = 0; i < n; i++) {              sum += a[i];          }           // Return the answer          return sum - n;      }            let a = [ 3, 4, 6 ];      let n = a.length;     document.write(maxModulosum(a, n));  </script> 

Output: 
10

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 


Next Article
Maximize the sum of Array by formed by adding pair of elements

A

anay07
Improve
Article Tags :
  • Greedy
  • Mathematical
  • Write From Home
  • DSA
  • Arrays
  • Modular Arithmetic
  • LCM
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Modular Arithmetic

Similar Reads

  • Maximize sum of chosen Array elements with value at most M
    Given an array arr[] of N positive numbers and an integer M. The task is to maximize the value of M by adding array elements when arr[i] ≤ M. Note: Any array element can be added at most once. Examples: Input: arr[] = {3, 9, 19, 5, 21}, M = 10Output: 67Explanation: One way to getthe value isM > 3
    4 min read
  • Maximize the sum of sum of the Array by removing end elements
    Given an array arr of size N, the task is to maximize the sum of sum, of the remaining elements in the array, by removing the end elements.Example: Input: arr[] = {2, 3} Output: 3 Explanation: At first we will delete 2, then sum of remaining elements = 3. Then delete 3. Therefore sum of sum = 3 + 0
    6 min read
  • Maximize total set bits of elements in N sized Array with sum M
    Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
    8 min read
  • Maximize score by multiplying elements of given Array with given multipliers
    Given two arrays array[] and multipliers[] of size N and M where N is always greater than equal to M. There are M operations to be performed. In each operation, choose multiplier[i] and an element from the array arr[] either from the start or the end let's say K then add multiplier[i]*K to the total
    9 min read
  • Maximize the sum of Array by formed by adding pair of elements
    Given an array a[] of 2*N integers, The task is to make the array a[] of size N i.e, reducing it to half size such that, a[i] = ?(a[j] + a[k]) / N?, 0 < j, k < 2*N - 1. and form the array so that the sum of all the elements of the array a[], will be maximum. Output the maximum sum. Examples: I
    6 min read
  • Maximum Sum of Array with given MEX
    Given 3 integers N, K, and X, the task is to construct an array arr[] with the below conditions: Size of the array = NMEX of the array = KAll array elements should be at most XAmong all the array that follows the above condition print the one having the maximum sum of its elements or print -1 if no
    7 min read
  • Maximize the sum of array by multiplying prefix of array with -1
    Given an array of elements 'arr', the task is to maximize the sum of the elements of this array after performing the following operation: You can take any prefix of 'arr' and multiply each element of the prefix with '-1'. In the first line, print the maximized sum than in the next line, print the in
    7 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Finding 'k' such that its modulus with each array element is same
    Given an array of n integers .We need to find all 'k' such that arr[0] % k = arr[1] % k = ....... = arr[n-1] % k Examples: Input : arr[] = {6, 38, 34}Output : 1 2 4 6%1 = 38%1 = 34%1 = 0 6%2 = 38%2 = 34%2 = 0 6%4 = 38%4 = 34%2 = 2Input : arr[] = {3, 2}Output : 1Suppose the array contains only two el
    8 min read
  • Maximize count of array elements required to obtain given sum
    Given an integer V and an array arr[] consisting of N integers, the task is to find the maximum number of array elements that can be selected from array arr[] to obtain the sum V. Each array element can be chosen any number of times. If the sum cannot be obtained, print -1. Examples: Input: arr[] =
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences