Find maximum in an array without using Relational Operators
Last Updated :
28 Apr, 2024
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));
Time Complexity: O(n), where n is the size of the input array
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem