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:
Find missing elements from an Array with duplicates
Next article icon

Find maximum in an array without using Relational Operators

Last Updated : 28 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of non-negative integers, find the maximum in the array without using Relational Operator.

Examples: 

Input : A[] = {2, 3, 1, 4, 5}
Output : 5

Input : A[] = {23, 17, 93}
Output : 93

We use repeated subtraction to find out the maximum. To find maximum between two numbers, we take a variable counter initialized to zero. We keep decreasing both the value till both of them becomes equal to zero (Note : The first value to become zero is no further decreased), increasing the counter simultaneously. While both the values becomes zero, the counter has increased to be the maximum of both of them. We first find the maximum of first two numbers and then compare it with the rest elements of the array one by one to find the overall maximum.

Below is the implementation of the above idea.

C++
#include <iostream> using namespace std;  // Function to find maximum between two non-negative // numbers without using relational operator. int maximum(int x, int y) {     int c = 0;      // Continues till both becomes zero.     while(x || y)     {         // decrement if the value is not already zero         if(x)         x--;          if(y)         y--;         c++;     }     return c; }  // Function to find maximum in an array. int arrayMaximum(int A[], int N) {     // calculating maximum of first two numbers     int mx = A[0];          // Iterating through each of the member of the array      // to calculate the maximum     for (int i = N-1; i; i--)          // Finding the maximum between current maximum         // and current value.         mx = maximum(mx, A[i]);          return mx; }  // Driver code int main()  {     // Array declaration      int A[] = {4, 8, 9, 18};     int N = sizeof(A) / sizeof(A[0]);          // Calling Function to find the maximum of the Array     cout << arrayMaximum(A, N);     return 0; }  
Java
import java.io.*;  class GFG {          // Function to find maximum between two      // non-negative numbers without using      // relational operator.     static int maximum(int x, int y)     {         int c = 0;          // Continues till both becomes zero.         while (x > 0 || y > 0) {                          // decrement if the value is not              // already zero             if (x > 0)                 x--;              if (y > 0)                 y--;             c++;         }                  return c;     }      // Function to find maximum in an array.     static int arrayMaximum(int A[], int N)     {                  // calculating maximum of first          // two numbers         int mx = A[0];          // Iterating through each of the          // member of the array to calculate         // the maximum         for (int i = N - 1; i > 0; i--)              // Finding the maximum between              // current maximum and current              // value.             mx = maximum(mx, A[i]);          return mx;     }      // Driver code     public static void main(String[] args)     {                  // Array declaration         int A[] = { 4, 8, 9, 18 };         int N = A.length;          // Calling Function to find the maximum         // of the Array         System.out.print(arrayMaximum(A, N));     } }  // This code is contributed by vt_m. 
Python3
# Function to find maximum between two  # non-negative numbers without using  # relational operator. def maximum(x, y):     c = 0      # Continues till both becomes zero.     while(x or y):                  # decrement if the value is          # not already zero         if(x):             x -= 1          if(y):             y -= 1         c += 1      return c  # Function to find maximum in an array. def arrayMaximum(A, N):          # calculating maximum of      # first two numbers     mx = A[0]          # Iterating through each of      # the member of the array      # to calculate the maximum     i = N - 1     while(i):                  # Finding the maximum between          # current maximum and current value.         mx = maximum(mx, A[i])         i -= 1          return mx  # Driver code if __name__ == '__main__':          # Array declaration      A = [4, 8, 9, 18]     N = len(A)          # Calling Function to find the      # maximum of the Array     print(arrayMaximum(A, N))      # This code is contributed by # Surendra_Gangwar 
C#
// C# program to Find maximum // in an array without using  // Relational Operators using System;  class GFG  {          // Function to find maximum      // between two non-negative     // numbers without using      // relational operator.     static int maximum(int x,                         int y)     {         int c = 0;          // Continues till          // both becomes zero.         while (x > 0 || y > 0)          {                          // decrement if              // the value is not              // already zero             if (x > 0)                 x--;              if (y > 0)                 y--;             c++;         }                  return c;     }      // Function to find      // maximum in an array.     static int arrayMaximum(int []A,                              int N)     {                  // calculating          // maximum of first          // two numbers         int mx = A[0];          // Iterating through          // each of the member         // of the array to          // calculate the maximum         for (int i = N - 1;                  i > 0; i--)              // Finding the maximum              // between current              // maximum and current              // value.             mx = maximum(mx, A[i]);          return mx;     }      // Driver code     public static void Main()     {                  // Array declaration         int []A = { 4, 8, 9, 18 };         int N = A.Length;          // Calling Function to         // find the maximum         // of the Array         Console.WriteLine(arrayMaximum(A, N));     } }  // This code is contributed // by anuj_67. 
JavaScript
    // Javascript program to Find maximum     // in an array without using      // Relational Operators          // Function to find maximum      // between two non-negative     // numbers without using      // relational operator.     function maximum(x, y)     {         let c = 0;            // Continues till          // both becomes zero.         while (x > 0 || y > 0)          {                            // decrement if              // the value is not              // already zero             if (x > 0)                 x--;                if (y > 0)                 y--;             c++;         }                    return c;     }        // Function to find      // maximum in an array.     function arrayMaximum(A, N)     {                    // calculating          // maximum of first          // two numbers         let mx = A[0];            // Iterating through          // each of the member         // of the array to          // calculate the maximum         for (let i = N - 1; i > 0; i--)                // Finding the maximum              // between current              // maximum and current              // value.             mx = maximum(mx, A[i]);            return mx;     }          // Array declaration     let A = [ 4, 8, 9, 18 ];     let N = A.length;      // Calling Function to     // find the maximum     // of the Array     console.log(arrayMaximum(A, N));          // This code is contributed by divyesh072019. 
PHP
<?php // Function to find maximum  // between two non-negative // numbers without using  // relational operator. function maximum($x, $y) {     $c = 0;      // Continues till      // both becomes zero.     while($x or $y)     {         // decrement if the value         // is not already zero         if($x)         $x--;          if($y)         $y--;         $c++;     }     return $c; }  // Function to find  // maximum in an array. function arrayMaximum($A, $N) {     // calculating maximum of     // first two numbers     $mx = $A[0];          // Iterating through each of      // the member of the array      // to calculate the maximum     for ( $i = $N - 1; $i; $i--)          // Finding the maximum         // between current maximum          // and current value.         $mx = maximum($mx, $A[$i]);          return $mx; }  // Driver code  // Array declaration  $A = array(4, 8, 9, 18); $N = count($A);  // Calling Function to find  // the maximum of the Array echo arrayMaximum($A, $N);  // This code is contributed // by anuj_67. ?> 

Output: 

18

Time complexity of the code will be O(N*max) where max is the maximum of the array elements.

Limitations : This will only work if the array contains all non negative integers.

Recursion Approach:

Follow the below steps:

  • Step 1:- Lets begin with the find_max function, which takes two arguments.
  • Step 2:- Ensure that the array size is equal to 1 (n = 1). If n is equal to 1 then return only element in the array as this is the maximum size.
  • Step 3:- If the size of the array is not 1 then call the find_max function recursively with the last element of the array (arr:n-1) & one less than n-1. This recursively returns the maximum element of the subarray that is formed by the last element.
  • Step 4:- For each subarray compare the result of the last element (arr [n-1]) to the result of the subarray. Then return the higher of the two values as the maximum value of the whole array.
  • Step 5:- To get the maximum element, call the function find_max with the array & the size.

Below is the implementation of the above approach: 

C++
#include <iostream> #include <vector>  using namespace std;  // Function to find the maximum element in an array // recursively int findMax(vector<int> arr, int n) {     // Base case     if (n == 1) {         return arr[0];     }     // Recursive case     return max(arr[n - 1], findMax(arr, n - 1)); }  int main() {     // Example usage     vector<int> arr = { 2, 3, 1, 4, 5 };      // Call the findMax function with the array and its size     cout << "Maximum element in the array: "          << findMax(arr, arr.size()) << endl;      return 0; } 
Java
public class MaxElementRecursive {      // Recursive function to find the maximum element in the     // array     public static int findMax(int[] arr, int n)     {         // Base case: if there is only one element in the         // array         if (n == 1) {             return arr[0];         }          // Recursive case: find the maximum of the current         // element and the maximum of the rest of the array         return Math.max(arr[n - 1], findMax(arr, n - 1));     }      // Example usage     public static void main(String[] args)     {         int[] arr = { 2, 3, 1, 4, 5 };          // Call the findMax function with the array and its         // size         int maxElement = findMax(arr, arr.length);         System.out.println("Maximum element in the array: "                            + maxElement);     } } 
Python3
# Define a recursive function to find the # maximum element in the array   def find_max(arr, n):     # Base case     if n == 1:         return arr[0]     # Recursive case     return max(arr[n-1], find_max(arr, n-1))   # Example usage arr = [2, 3, 1, 4, 5]  # Call the find_max function with the array and its size print(find_max(arr, len(arr))) 
JavaScript
function findMax(arr, n) {     // Base case     if (n === 1) {         return arr[0];     }     // Recursive case     return Math.max(arr[n - 1], findMax(arr, n - 1)); }  // Example usage const arr = [2, 3, 1, 4, 5];  // Call the findMax function with the array and its size console.log(findMax(arr, arr.length)); 

Output
5 

Time Complexity: O(n), where n is the size of the input array

Auxiliary Space: O(n)




Next Article
Find missing elements from an Array with duplicates

S

ShivamKD
Improve
Article Tags :
  • Arrays
  • DSA
  • programming-puzzle
Practice Tags :
  • Arrays

Similar Reads

  • Search in an Array of Rational Numbers without floating point arithmetic
    Given a sorted array of rational numbers, where each rational number is represented in the form p/q (where p is the numerator and q is the denominator), the task is to find the index of a given rational number x in the array. If the number does not exist in the array, return -1. Examples: Input: arr
    9 min read
  • Find the Target number in an Array
    Finding a number within an array is an operation, in the field of computer science and data analysis. In this article, we will discuss the steps involved and analyze their time and space complexities. Examples: Input: Array: {10, 20, 30, 40, 50} , Target: 30Output: "Target found at index 2" Input: A
    13 min read
  • Find all pairs with a given sum in two unsorted arrays
    Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X. Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3 Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output:
    13 min read
  • Maximum XOR Queries With an Element From Array
    Given an array arr[] of size n containing non-negative integers and also given a list of q queries in a 2D array queries[][], where each query is of the form [xi, mi]. For each query, you need to find the maximum value of (xi XOR arr[j]) such that arr[j] is less than or equal to mi. In simple terms,
    15+ min read
  • Find missing elements from an Array with duplicates
    Given an array arr[] of size N having integers in the range [1, N] with some of the elements missing. The task is to find the missing elements. Note: There can be duplicates in the array. Examples: Input: arr[] = {1, 3, 3, 3, 5}, N = 5Output: 2 4Explanation: The numbers missing from the list are 2 a
    12 min read
  • Range Update Queries to XOR with 1 in a Binary Array.
    Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [
    15+ min read
  • Find a String in given Array of Strings using Binary Search
    Given a sorted array of Strings arr and a string x, The task is to find the index of x in the array using the Binary Search algorithm. If x is not present, return -1. Examples: Input: arr[] = {"contribute", "geeks", "ide", "practice"}, x = "ide"Output: 2Explanation: The String x is present at index
    6 min read
  • Find the two repeating elements in a given array
    Given an array arr[] of N+2 elements. All elements of the array are in the range of 1 to N. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. Examples: Input: arr = [4, 2, 4, 5, 2, 3, 1], N = 5Output: 4 2Explanation: The above array has n + 2 = 7 eleme
    15+ min read
  • Searching Elements in an Array | Array Operations
    In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as: Searching in an Unsorted Array using Linear SearchSearching in a Sorted Array using Linear SearchSearching in a Sorted Array using Binary SearchSearching in an Sorted Array using Fibona
    15+ min read
  • Find all pairs (a,b) and (c,d) in array which satisfy ab = cd
    Given an array of distinct integers, the task is to find two pairs (a, b) and (c, d) such that ab = cd, where a, b, c and d are distinct elements. Examples: Input : arr[] = {3, 4, 7, 1, 2, 9, 8} Output : 4 2 and 1 8 Product of 4 and 2 is 8 and also product of 1 and 8 is 8 . Input : arr[] = {1, 6, 3,
    7 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