×

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j

For example

Input:

N = 2

A[] = {1, 20}

Output:

1

Explanation:

A[0]<A[1] so (j-i) is 1-0 = 1.

Input:

N = 10

A[] = {9, 2, 3, 4, 5, 6, 7, 8, 18, 0}

Output:

8

Explanation:

In the given array A[0] < A[8]

satisfying the required condition(A[i] < A[j]) thus giving the maximum difference of j - i which is 8(8-0).

Approach 1

The approach is simple but inefficient. Run two loops. The outer loop will pick the element from the left and the inner loop will pick the element from the right.

Check if the element picked in the inner loop is greater than the element picked in the outer loop. Stop the inner loop and store the difference of (j-i).

Likewise, do the process for the entire array and update the maximum difference of (j-i).

Code (C++)

#include <bits/stdc++.h>

using namespace std;

// Function to find the max difference

int maxIndexDiff(int arr[], int n)

{

          int maxDiff = -1; // Let current max diff is -1

          int i, j; // Initialize two variables




          for (i = 0; i < n; ++i) { // outer loop

                   for (j = n - 1; j > i; --j) { // inner loop

                             if (arr[j] > arr[i] && maxDiff < (j - i)) // if element is greater and current maxdiff is less than the new one update the maxdiff

                                      maxDiff = j - i;

                   }

          }




          return maxDiff; // return the max difference

}




int main()

{

          int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };

          int n = sizeof(arr) / sizeof(arr[0]); // Find the size of the array

          int maxDiff = maxIndexDiff(arr, n); // Call the function to calculate maximum difference

          cout << "Maximum difference is " << maxDiff;

          return 0;

}

Output

Maximum difference is 8

Code (C language)

#include <stdio.h>

// Function to find the max difference

int maxIndexDiff(int arr[], int n)

{

          int maxDiff = -1; // Let current max diff is -1

          int i, j; // Initialize two variables




          for (i = 0; i < n; ++i) { // outer loop

                   for (j = n - 1; j > i; --j) { // inner loop

                             if (arr[j] > arr[i] && maxDiff < (j - i)) // if element is greater and current maxdiff is less than the new one update the maxdiff

                                      maxDiff = j - i;

                   }

          }




          return maxDiff; // return the max difference

}




int main()

{

          int arr[] = { 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 };

          int n = sizeof(arr) / sizeof(arr[0]); // Find the size of the array

          int maxDiff = maxIndexDiff(arr, n); // Call the function to calculate maximum difference

          printf("Maximum difference is %d", maxDiff);

          return 0;

}

Output

Maximum difference is 8

Time complexity - O(n*n)

Approach 2

After analyzing the brute force approach, it is observed that for every element in the outer loop, we find the maximum in the inner loop. This means for every window we find a maximum element.

For example, in A =  [1, 5, 12, 4, 9]

9 is greater than 1, 5, 4. Now to avoid finding the maximum again and again we can keep the track of the maximum number moving from the end to start of the array.

  1. Traverse the array from the end and keep a track of the maximum number to the right of the current index including self.
  2. Now we have a monotonous decreasing array, and we know we can use binary search to find the index of the rightmost greater element
  3. Now we will just use binary search for each of the elements in the array and store the maximum difference of the indices and that’s it we are done.

Code

#include <bits/stdc++.h>

using namespace std;

int main()

{

          vector<long long int> v{ 9, 2, 3, 4, 5, 6, 7, 8, 18, 0 }; // Take a vector

          int n = v.size(); // Find the size of the vector

          vector<long long int> maxFromEnd(n + 1, INT_MIN); // A vector to keep the max from end




          // create an array maxfromEnd

          for (int i = v.size() - 1; i >= 0; i--) {

                   maxFromEnd[i] = max(maxFromEnd[i + 1], v[i]);

          }




          int result = 0; //store max difference as result




          // use  binary search here

          for (int i = 0; i < v.size(); i++) {

// set low and high pointer

                   int low = i + 1, high = v.size() - 1, ans = i;




                   while (low <= high) {

                             int mid = (low + high) / 2; // find the mid element




                             if (v[i] <= maxFromEnd[mid]) {

                           

                                      // We store this as current answer and look

                                      // for further larger number to the right

                                      // side

                                      ans = max(ans, mid); // calculate current max diff

                                      low = mid + 1;

                             }

                             else {

                                      high = mid - 1;

                             }

                   }

                   // keeping a track of the

                   // maximum difference in indices

                   result = max(result, ans - i);

          }

          cout <<"Maximum difference is " << result << endl;

}

Output

Maximum difference is 8

Time complexity - O(n * logn)

Approach 3

By taking special care of the duplicates the problem can be solved in less than quadratic complexity.

  • To handle the duplicates, traverse the array and store each element index in a list.
  • Sort the array and then traverse it by keeping track of the maximum difference of i and j.
  • For j, the last index of the list will be taken and for i keep the first index from the list.
  • Update the maximum index and traverse the array upto last.

Code

#include <bits/stdc++.h>

using namespace std;

int maxIndexDiff(vector<int>& arr, int n) // Function to find max difference

{




          unordered_map<int, vector<int> > hashmap; // create unordered map




// Loop till the array end

          for (int i = 0; i < n; i++) {

                   hashmap[arr[i]].push_back(i); // Insert the index of a particular element

          }




          // Sort arr

          sort(arr.begin(), arr.end());

          int maxDiff = INT_MIN; // Let max difference is mimimum in the begining

          int temp = n; // take the size of array in temp




          // Iterate in the array

          for (int i = 0; i < n; i++) {

                   if (temp > hashmap[arr[i]][0]) { // Compare the index to avoid overflow

                             temp = hashmap[arr[i]][0];

                   }

                   maxDiff = max( // find max difference

                             maxDiff,

                             hashmap[arr[i]][hashmap[arr[i]].size() - 1]

                                      - temp);

          }

          return maxDiff; // return max difference

}




int main()

{




          int n = 9; // size of vector

          vector<int> arr{ 34, 8, 10, 3, 2, 80, 30, 33, 1 }; // vector elements




          int ans = maxIndexDiff(arr, n); // call the function

          cout << "The maxIndexDiff is : " << ans << endl; // print the result




          return 1;

}

Output

The maxIndexDiff is: 6

Time complexity

O(nlogn)

Space complexity

O(1)


Related Topics

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Sliding Window Technique in C++

Sliding Window Technique or Window Sliding Technique is a computational technique that is mainly used to reduce the use of nested loop and replace it with a single loop. It...

4 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

Reverse String Word-Wise in C++

What is a reversed String? Reversing the words of a sentence is called reversed string by words. The difference between the reverse a string and the reverse a string word-wise is...

4 minutes read.

C++ Aggregation

C++ Aggregation Definition: In C++, aggregation is a process in which one class (as an entity reference) defines another class. It provides another way to reuse the class. It represents...

4 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.