Maximum absolute difference of value and index sums
Last Updated :
29 Jul, 2022
Given an unsorted array A of N integers, A_{1}, A_{2}, ...., A_{N}. Return maximum value of f(i, j) for all 1 ? i, j ? N.
f(i, j) or absolute difference of two elements of an array A is defined as |A[i] - A[j]| + |i - j|, where |A| denotes the absolute value of A.
Examples:
We will calculate the value of f(i, j) for each pair
of (i, j) and return the maximum value thus obtained.
Input : A = {1, 3, -1}
Output : 5
f(1, 1) = f(2, 2) = f(3, 3) = 0
f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3
f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4
f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5
So, we return 5.
Input : A = {3, -2, 5, -4}
Output : 10
f(1, 1) = f(2, 2) = f(3, 3) = f(4, 4) = 0
f(1, 2) = f(2, 1) = |3 - (-2)| + |1 - 2| = 6
f(1, 3) = f(3, 1) = |3 - 5| + |1 - 3| = 4
f(1, 4) = f(4, 1) = |3 - (-4)| + |1 - 4| = 10
f(2, 3) = f(3, 2) = |(-2) - 5| + |2 - 3| = 8
f(2, 4) = f(4, 2) = |(-2) - (-4)| + |2 - 4| = 4
f(3, 4) = f(4, 3) = |5 - (-4)| + |3 - 4| = 10
So, we return 10
A naive brute force approach is to calculate the value f(i, j) by iterating over all such pairs (i, j) and calculating the maximum absolute difference which is implemented below.
Implementation:
C++
// Brute force C++ program to calculate the
// maximum absolute difference of an array.
#include <bits/stdc++.h>
using namespace std;
int calculateDiff(int i, int j, int arr[])
{
// Utility function to calculate
// the value of absolute difference
// for the pair (i, j).
return abs(arr[i] - arr[j]) + abs(i - j);
}
// Function to return maximum absolute
// difference in brute force.
int maxDistance(int arr[], int n)
{
// Variable for storing the maximum
// absolute distance throughout the
// traversal of loops.
int result = 0;
// Iterate through all pairs.
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// If the absolute difference of
// current pair (i, j) is greater
// than the maximum difference
// calculated till now, update
// the value of result.
if (calculateDiff(i, j, arr) > result)
result = calculateDiff(i, j, arr);
}
}
return result;
}
// Driver program to test the above function.
int main()
{
int arr[] = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxDistance(arr, n) << endl;
return 0;
}
Java
// Java program to calculate the maximum
// absolute difference of an array.
public class MaximumAbsoluteDifference
{
private static int calculateDiff(int i, int j,
int[] array)
{
// Utility function to calculate
// the value of absolute difference
// for the pair (i, j).
return Math.abs(array[i] - array[j]) +
Math.abs(i - j);
}
// Function to return maximum absolute
// difference in brute force.
private static int maxDistance(int[] array)
{
// Variable for storing the maximum
// absolute distance throughout the
// traversal of loops.
int result = 0;
// Iterate through all pairs.
for (int i = 0; i < array.length; i++)
{
for (int j = i; j < array.length; j++)
{
// If the absolute difference of
// current pair (i, j) is greater
// than the maximum difference
// calculated till now, update
// the value of result.
result = Math.max(result, calculateDiff(i, j, array));
}
}
return result;
}
// Driver program to test above function
public static void main(String[] args)
{
int[] array = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
System.out.println(maxDistance(array));
}
}
// This code is contributed by Harikrishnan Rajan
Python3
# Brute force Python 3 program
# to calculate the maximum
# absolute difference of an array.
def calculateDiff(i, j, arr):
# Utility function to calculate
# the value of absolute difference
# for the pair (i, j).
return abs(arr[i] - arr[j]) + abs(i - j)
# Function to return maximum
# absolute difference in
# brute force.
def maxDistance(arr, n):
# Variable for storing the
# maximum absolute distance
# throughout the traversal
# of loops.
result = 0
# Iterate through all pairs.
for i in range(0,n):
for j in range(i, n):
# If the absolute difference of
# current pair (i, j) is greater
# than the maximum difference
# calculated till now, update
# the value of result.
if (calculateDiff(i, j, arr) > result):
result = calculateDiff(i, j, arr)
return result
# Driver program
arr = [ -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 ]
n = len(arr)
print(maxDistance(arr, n))
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to calculate the maximum
// absolute difference of an array.
using System;
public class MaximumAbsoluteDifference
{
private static int calculateDiff(int i, int j,
int[] array)
{
// Utility function to calculate
// the value of absolute difference
// for the pair (i, j).
return Math.Abs(array[i] - array[j]) +
Math.Abs(i - j);
}
// Function to return maximum absolute
// difference in brute force.
private static int maxDistance(int[] array)
{
// Variable for storing the maximum
// absolute distance throughout the
// traversal of loops.
int result = 0;
// Iterate through all pairs.
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length; j++)
{
// If the absolute difference of
// current pair (i, j) is greater
// than the maximum difference
// calculated till now, update
// the value of result.
result = Math.Max(result, calculateDiff(i, j, array));
}
}
return result;
}
// Driver program
public static void Main()
{
int[] array = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
Console.WriteLine(maxDistance(array));
}
}
// This code is contributed by vt_m
PHP
<?php
// Brute force PHP program to
// calculate the maximum absolute
// difference of an array.
function calculateDiff($i, $j, $arr)
{
// Utility function to calculate
// the value of absolute difference
// for the pair (i, j).
return abs($arr[$i] - $arr[$j]) +
abs($i - $j);
}
// Function to return maximum
// absolute difference in brute force.
function maxDistance($arr, $n)
{
// Variable for storing the maximum
// absolute distance throughout the
// traversal of loops.
$result = 0;
// Iterate through all pairs.
for ($i = 0; $i < $n; $i++)
{
for ($j = $i; $j < $n; $j++)
{
// If the absolute difference of
// current pair (i, j) is greater
// than the maximum difference
// calculated till now, update
// the value of result.
if (calculateDiff($i, $j, $arr) > $result)
$result = calculateDiff($i, $j, $arr);
}
}
return $result;
}
// Driver Code
$arr = array( -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 );
$n = sizeof($arr);
echo maxDistance($arr, $n);
// This Code is contributed by mits
?>
JavaScript
<script>
// javascript program to calculate the maximum
// absolute difference of an array.
let MAX = 256;
// Function to count the number of equal pairs
function calculateDiff(i, j, array)
{
// Utility function to calculate
// the value of absolute difference
// for the pair (i, j).
return Math.abs(array[i] - array[j]) +
Math.abs(i - j);
}
// Function to return maximum absolute
// difference in brute force.
function maxDistance(array)
{
// Variable for storing the maximum
// absolute distance throughout the
// traversal of loops.
let result = 0;
// Iterate through all pairs.
for (let i = 0; i < array.length; i++)
{
for (let j = i; j < array.length; j++)
{
// If the absolute difference of
// current pair (i, j) is greater
// than the maximum difference
// calculated till now, update
// the value of result.
result = Math.max(result, calculateDiff(i, j, array));
}
}
return result;
}
// Driver Function
let array = [-70, -64, -6, -56, 64,
61, -57, 16, 48, -98 ];
document.write(maxDistance(array));
// This code is contributed by susmitakundugoaldanga.
</script>
Time complexity: O(n2)
Auxiliary Space: O(1)
An efficient solution in O(n) time complexity can be worked out using the properties of absolute values.
f(i, j) = |A[i] - A[j]| + |i - j| can be written in 4 ways (Since we are looking at max value, we don’t even care if the value becomes negative as long as we are also covering the max value in some way).
Case 1: A[i] > A[j] and i > j
|A[i] - A[j]| = A[i] - A[j]
|i -j| = i - j
hence, f(i, j) = (A[i] + i) - (A[j] + j)
Case 2: A[i] < A[j] and i < j
|A[i] - A[j]| = -(A[i]) + A[j]
|i -j| = -(i) + j
hence, f(i, j) = -(A[i] + i) + (A[j] + j)
Case 3: A[i] > A[j] and i < j
|A[i] - A[j]| = A[i] - A[j]
|i -j| = -(i) + j
hence, f(i, j) = (A[i] - i) - (A[j] - j)
Case 4: A[i] < A[j] and i > j
|A[i] - A[j]| = -(A[i]) + A[j]
|i -j| = i - j
hence, f(i, j) = -(A[i] - i) + (A[j] - j)
Note that cases 1 and 2 are equivalent and so are cases 3 and 4 and hence we can design our algorithm only for two cases as it will cover all the possible cases.
1. Calculate the value of A[i] + i and A[i] - i for every element of the array while traversing through the array.
2. Then for the two equivalent cases, we find the maximum possible value. For that, we have to store minimum and maximum values of expressions A[i] + i and A[i] - i for all i.
3. Hence the required maximum absolute difference is maximum of two values i.e. max((A[i] + i) - (A[j] + j)) and max((A[i] - i) - (A[j] - j)). These values can be found easily in linear time.
a. For max((A[i] + i) - (A[j] + j)) Maintain two variables max1 and min1 which will store maximum and minimum values of A[i] + i respectively. max((A[i] + i) - (A[j] + j)) = max1 - min1
b. For max((A[i] - i) - (A[j] - j)). Maintain two variables max2 and min2 which will store maximum and minimum values of A[i] - i respectively. max((A[i] - i) - (A[j] - j)) = max2 - min2
Implementation using the above fast algorithm is given below.
C++
// C++ program to calculate the maximum
// absolute difference of an array.
#include <bits/stdc++.h>
using namespace std;
// Function to return maximum absolute
// difference in linear time.
int maxDistance(int arr[], int n)
{
// max and min variables as described
// in algorithm.
int max1 = INT_MIN, min1 = INT_MAX;
int max2 = INT_MIN, min2 = INT_MAX;
for (int i = 0; i < n; i++) {
// Updating max and min variables
// as described in algorithm.
max1 = max(max1, arr[i] + i);
min1 = min(min1, arr[i] + i);
max2 = max(max2, arr[i] - i);
min2 = min(min2, arr[i] - i);
}
// Calculating maximum absolute difference.
return max(max1 - min1, max2 - min2);
}
// Driver program to test the above function.
int main()
{
int arr[] = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << maxDistance(arr, n) << endl;
return 0;
}
Java
// Java program to calculate the maximum
// absolute difference of an array.
public class MaximumAbsoluteDifference
{
// Function to return maximum absolute
// difference in linear time.
private static int maxDistance(int[] array)
{
// max and min variables as described
// in algorithm.
int max1 = Integer.MIN_VALUE;
int min1 = Integer.MAX_VALUE;
int max2 = Integer.MIN_VALUE;
int min2 = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++)
{
// Updating max and min variables
// as described in algorithm.
max1 = Math.max(max1, array[i] + i);
min1 = Math.min(min1, array[i] + i);
max2 = Math.max(max2, array[i] - i);
min2 = Math.min(min2, array[i] - i);
}
// Calculating maximum absolute difference.
return Math.max(max1 - min1, max2 - min2);
}
// Driver program to test above function
public static void main(String[] args)
{
int[] array = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
System.out.println(maxDistance(array));
}
}
// This code is contributed by Harikrishnan Rajan
Python3
# Python program to
# calculate the maximum
# absolute difference
# of an array.
# Function to return
# maximum absolute
# difference in linear time.
def maxDistance(array):
# max and min variables as described
# in algorithm.
max1 = -2147483648
min1 = +2147483647
max2 = -2147483648
min2 = +2147483647
for i in range(len(array)):
# Updating max and min variables
# as described in algorithm.
max1 = max(max1, array[i] + i)
min1 = min(min1, array[i] + i)
max2 = max(max2, array[i] - i)
min2 = min(min2, array[i] - i)
# Calculating maximum absolute difference.
return max(max1 - min1, max2 - min2)
# Driver program to
# test above function
array = [ -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 ]
print(maxDistance(array))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to calculate the maximum
// absolute difference of an array.
using System;
public class MaximumAbsoluteDifference
{
// Function to return maximum absolute
// difference in linear time.
private static int maxDistance(int[] array)
{
// max and min variables as described
// in algorithm.
int max1 = int.MinValue ;
int min1 = int.MaxValue ;
int max2 = int.MinValue ;
int min2 =int.MaxValue ;
for (int i = 0; i < array.Length; i++)
{
// Updating max and min variables
// as described in algorithm.
max1 = Math.Max(max1, array[i] + i);
min1 = Math.Min(min1, array[i] + i);
max2 = Math.Max(max2, array[i] - i);
min2 = Math.Min(min2, array[i] - i);
}
// Calculating maximum absolute difference.
return Math.Max(max1 - min1, max2 - min2);
}
// Driver program
public static void Main()
{
int[] array = { -70, -64, -6, -56, 64,
61, -57, 16, 48, -98 };
Console.WriteLine(maxDistance(array));
}
}
// This code is contributed by vt_m
PHP
<?php
// PHP program to calculate the maximum
// absolute difference of an array.
// Function to return maximum absolute
// difference in linear time.
function maxDistance( $arr, $n)
{
// max and min variables as
// described in algorithm.
$max1 = PHP_INT_MIN; $min1 =
PHP_INT_MAX;
$max2 = PHP_INT_MIN;$min2 =
PHP_INT_MAX;
for($i = 0; $i < $n; $i++)
{
// Updating max and min variables
// as described in algorithm.
$max1 = max($max1, $arr[$i] + $i);
$min1 = min($min1, $arr[$i] + $i);
$max2 = max($max2, $arr[$i] - $i);
$min2 = min($min2, $arr[$i] - $i);
}
// Calculating maximum
// absolute difference.
return max($max1 - $min1,
$max2 - $min2);
}
// Driver Code
$arr = array(-70, -64, -6, -56, 64,
61, -57, 16, 48, -98);
$n = count($arr);
echo maxDistance($arr, $n);
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// JavaScript program to calculate the maximum
// absolute difference of an array.
// Function to return maximum absolute
// difference in linear time.
function maxDistance(array)
{
// max and min variables as described
// in algorithm.
let max1 = Number.MIN_VALUE;
let min1 = Number.MAX_VALUE;
let max2 = Number.MIN_VALUE;
let min2 = Number.MAX_VALUE;
for (let i = 0; i < array.length; i++)
{
// Updating max and min variables
// as described in algorithm.
max1 = Math.max(max1, array[i] + i);
min1 = Math.min(min1, array[i] + i);
max2 = Math.max(max2, array[i] - i);
min2 = Math.min(min2, array[i] - i);
}
// Calculating maximum absolute difference.
return Math.max(max1 - min1, max2 - min2);
}
let array =
[ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ];
document.write(maxDistance(array));
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
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