Given an array arr[], the task is to find the array formed from the difference of each element from the largest element in the given array.
Example:
Input: arr[] = {3, 6, 9, 2,6}
Output: {6, 3, 0, 7, 3}
Explanation:
Largest element of the array = 9
Therefore difference of arr[i] from 9:
Element 1: 9 – 3 = 6
Element 2: 9 – 6 = 3
Element 3: 9 – 9 = 0
Element 4: 9 – 2 = 7
Element 5: 9 – 6 = 3
Hence the output will be {6, 3, 0, 7, 3}
Input: arr[] = {7, 2, 5, 6, 3, 1, 6, 9}
Output: {2, 7, 4, 3, 6, 8, 3, 0}
Approach:
Find the largest of n elements in an array and store it in a variable largest. Now check the difference between the largest and the other elements in the array.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int difference( int arr[], int n)
{
int largest = arr[0];
int i;
for (i = 0; i < n; i++) {
if (largest < arr[i])
largest = arr[i];
}
for (i = 0; i < n; i++)
arr[i] = largest - arr[i];
for (i = 0; i < n; i++)
cout << arr[i] << " " ;
}
int main()
{
int arr[] = { 10, 5, 9, 3, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
difference(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static void difference( int arr[], int n)
{
int largest = arr[ 0 ];
int i;
for (i = 0 ; i < n; i++)
{
if (largest < arr[i])
largest = arr[i];
}
for (i = 0 ; i < n; i++)
arr[i] = largest - arr[i];
for (i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
public static void main(String[] args)
{
int arr[] = { 10 , 5 , 9 , 3 , 2 };
int n = arr.length;
difference(arr, n);
}
}
|
Python3
def difference(arr, n):
largest = arr[ 0 ];
i = 0 ;
for i in range (n):
if (largest < arr[i]):
largest = arr[i];
for i in range (n):
arr[i] = largest - arr[i];
for i in range (n):
print (arr[i], end = " " );
if __name__ = = '__main__' :
arr = [ 10 , 5 , 9 , 3 , 2 ];
n = len (arr);
difference(arr, n);
|
C#
using System;
class GFG
{
static void difference( int []arr, int n)
{
int largest = arr[0];
int i;
for (i = 0; i < n; i++)
{
if (largest < arr[i])
largest = arr[i];
}
for (i = 0; i < n; i++)
arr[i] = largest - arr[i];
for (i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
public static void Main(String[] args)
{
int []arr = { 10, 5, 9, 3, 2 };
int n = arr.Length;
difference(arr, n);
}
}
|
Javascript
<script>
function difference(arr, n)
{
let largest = arr[0];
let i;
for (i = 0; i < n; i++)
{
if (largest < arr[i])
largest = arr[i];
}
for (i = 0; i < n; i++)
arr[i] = largest - arr[i];
for (i = 0; i < n; i++)
document.write(arr[i] + " " );
}
let arr = [10, 5, 9, 3, 2];
let n = arr.length;
difference(arr, n);
</script>
|
Time complexity: O(n)
Auxiliary space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
16 Oct, 2022
Like Article
Save Article