adspace


Given an array of integers, devise a program to replace every element with the next greatest element on the right side in the array. Also, replace the last element with 5 as there no element on the right side of it.

Answer Posted / Lokendra Singh Thakur

Algorithm:
1. Initialize a variable 'nextGreater' to store the next greater element. Set it to -1 for all elements.
2. Iterate through the array from the end towards the beginning, updating 'nextGreater' values as you go.
3. After finding the 'nextGreater' value for an element, move backwards in the array and replace the current element with its 'nextGreater' value if it is greater than the current one.
4. Replace the last element with 5.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What sort of serious problems have you experienced, and how have you handled them?

1033


For the following COBOL code, draw the Binary tree? 01 STUDENT_REC. 02 NAME. 03 FIRST_NAME PIC X(10). 03 LAST_NAME PIC X(10). 02 YEAR_OF_STUDY. 03 FIRST_SEM PIC XX. 03 SECOND_SEM PIC XX.

1403


Can you declare an array without assigning the size of an array?

1223


“int a[] = new int[3]{1, 2, 3}” – This a legal way of defining the arrays?

1292


Draw a binary Tree for the expression : A * B - (C + D) * (P / Q)

1506


Write a program for Sorting an Array. Which sorting will you prefer?

1047