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 cost of reducing array elements
Next article icon

Maximize sum of chosen Array elements with value at most M

Last Updated : 13 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 10
Output: 67
Explanation: One way to getthe value is
M > 3; 3 is added to M and it becomes 10+3 = 13
M > 9; 9 is added to M and it becomes 13+9 = 22
M > 19; 19 is added to M and it becomes 22+19 = 41
M > 5; 5 is added to M and it becomes 41+5 = 46
M > 21; 21 is added to M and it becomes 46+21 = 67
Thus, M = 67 at the end.

Input: arr[] = {2, 13, 4, 19}, M = 6
Output: 12
Explanation: One way to get the value is
M > 4; 4 is added to M and it becomes 6+4 = 10
M > 2; 2 is added to M and it becomes 10+2 = 12
No other value in the array is smaller or equal to M.
Thus, M is 12 at the end.

 

Approach: The solution is based on the concept of sorting. Follow the steps mentioned below:

  • First, sort the array in increasing order.
  • For every index i, from 0 to N-1, do the following:
    • If M ≥ arr[i], add arr[i] with M.
    • If M< arr[i], stop iteration.
  • Return the final value of M as the answer.

Below is the implementation of the above approach.

C++
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std;  // Function to calculate // the maximum value of M // that can be obtained int IsArrayHungry(int M, vector<int>& arr) {     // Sort the array in increasing order.     sort(arr.begin(), arr.end());     long long sum = M;     int N = arr.size();      for (int i = 0; i < N; i++) {         if (sum >= arr[i])             sum += arr[i];         else             break;     }     return sum; }  // Driver code int main() {     vector<int> arr{ 3, 9, 19, 5, 21 };     int M = 10;     int res = IsArrayHungry(M, arr);     cout << res;     return 0; } 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  class GFG {    // Function to calculate   // the maximum value of M   // that can be obtained   static int IsArrayHungry(int M, int arr[ ])   {      // Sort the array in increasing order.     Arrays.sort(arr);     int sum = M;     int N = arr.length;      for (int i = 0; i < N; i++) {       if (sum >= arr[i])         sum += arr[i];       else         break;     }     return sum;   }    // Driver code   public static void main (String[] args)   {     int arr[ ] = { 3, 9, 19, 5, 21 };     int M = 10;     int res = IsArrayHungry(M, arr);     System.out.print(res);   } }  // This code is contributed by hrithikgarg03188. 
Python3
# Python 3 code to implement the approach  # Function to calculate # the maximum value of M # that can be obtained def IsArrayHungry(M,  arr):      # Sort the array in increasing order.     arr.sort()     sum = M     N = len(arr)      for i in range(N):         if (sum >= arr[i]):             sum += arr[i]          else:             break      return sum  # Driver code if __name__ == "__main__":      arr = [3, 9, 19, 5, 21]     M = 10     res = IsArrayHungry(M, arr)     print(res)      # This code is contributed by ukasp. 
C#
// C# code to implement above approach using System; class GFG {    // Function to calculate   // the maximum value of M   // that can be obtained   static int IsArrayHungry(int M, int []arr)   {      // Sort the array in increasing order.     Array.Sort(arr);     int sum = M;     int N = arr.Length;      for (int i = 0; i < N; i++) {       if (sum >= arr[i])         sum += arr[i];       else         break;     }     return sum;   }    // Driver Code:   public static void Main()   {     int []arr = { 3, 9, 19, 5, 21 };     int M = 10;     int res = IsArrayHungry(M, arr);     Console.WriteLine(res);   } }  // This code is contributed by Samim Hossain Mondal. 
JavaScript
<script>         // JavaScript code for the above approach           // Function to calculate         // the maximum value of M         // that can be obtained         function IsArrayHungry(M, arr)         {                      // Sort the array in increasing order.             arr.sort(function (a, b) { return a - b })             let sum = M;             let N = arr.length;              for (let i = 0; i < N; i++) {                 if (sum >= arr[i])                     sum += arr[i];                 else                     break;             }             return sum;         }          // Driver code         let arr = [3, 9, 19, 5, 21];         let M = 10;         let res = IsArrayHungry(M, arr);         document.write(res);    // This code is contributed by Potta Lokesh     </script> 

 
 


Output
67


 

Time Complexity: O(N * logN)
Auxiliary Space: O(1), since no extra space has been added.


 


Next Article
Maximize the cost of reducing array elements
author
pintusaini
Improve
Article Tags :
  • Sorting
  • Algo Geek
  • DSA
  • Arrays
  • Algo-Geek 2021
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Maximize the sum of modulus with every Array element
    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)
    4 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
  • Covering maximum array elements with given value
    Given total number of candies 'X', number of students 'N' and an array 'arr' which holds the value for the exact number of candies that must be given to a student to make the student happy where arr[i] is the exact amount of candies that make the student 'i' happy. The task is to distribute the cand
    7 min read
  • Maximize the cost of reducing array elements
    Given an array arr[] of N positive integers. We can choose any one index(say K) of the array and reduce all the elements of the array from index 0 to K - 1 by 1. The cost of this operation is K. If at any index(say idx) element is reduced to 0 then we can't perform this operation in the range [idx,
    6 min read
  • Maximize count of K unique elements that can be chosen from Array
    Given an arrays arr[] of size N and an array of queries Q[] of size M, where Q[i] defines the count of unique elements that have to be chosen from the array arr[]. The task to find the maximum number of elements that can be picked for each query. Examples: Input: arr[ ] = {30, 31, 32, 33, 32, 32, 31
    6 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
  • Maximize array sum by replacing at most L elements to R for Q queries
    Given an array arr[] consisting of N integers and an array Query[][] consisting of M pairs of the type {L, R}, the task is to find the maximum sum of the array by performing the queries Query[][] such that for each query {L, R} replace at most L array elements to the value R. Examples: Input: arr[]=
    7 min read
  • Longest Sub-array with maximum average value
    Given an array arr[] of n integers. The task is to find the maximum length of the sub-array which has the maximum average value (average of the elements of the sub-array). [Tex] [/Tex]Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 1 {6} is the required sub-arrayInput: arr[] = {6, 1, 6, 6, 0} Outpu
    6 min read
  • Maximize the first element of the array such that average remains constant
    Given an array arr[] of length N and an integer X, the task is to find the maximum value R of updated first element such that the average of the array remains constant and no elements of the array should become negative. The maximum value of the first element should be in the range arr[0] <= R
    6 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