Open In App

Reaching the heighest floor

Last Updated : 15 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The teacher gives a mental ability question to Raju. The question is as follows:-

Raju is in an elevator. Given by his teacher is an array of size N which denotes the number of floors and has a 1-based indexing. The elevator starts from the ground and moves up and down, X and Y floors respectively. There is a code used in the elevator according to which it moves up X floors given at odd indexes of the array and moves down Y floors given at even indexes of the array. He is asked to go to the highest floor possible. Help him to sort the array such that he reaches the highest floor after traversing the whole array from starting till the end, without skipping any index.

He always prefers to move more number of floors up and less number of floors down. Once he gets into the elevator, the elevator should not reach the ground again, if it does return -1.

Examples:

Input: arr[ ] = {2, 3, 4, 5}
Output: 5 2 4 3
Explanation: Array can be arranged as {5, 3, 4, 2} or {4, 3, 5, 2} or {4, 2, 5, 3} but it will get arranged as {5, 2, 4, 3} because he always prefer to move more number of floors up and less number of floors down.

Input: arr[ ] = {1, 1} 
Output: Not Possible

Approach: To solve the problem follow the below idea:

We must identify the arrangement that will allow Raju to ascend to the top floor. To achieve this, we must place the larger components on the array’s odd indexes and the smaller elements on its even ones.

Below are the steps to solve this problem.

  • Make an empty ArrayList v to hold the heights that are produced.
  • Add the only element of the array a[] to v if n = 1, then return v.
  • The built-in Arrays.sort() method can be used to sort the array a[] in ascending order.
  • Compare the beginning and last members of the array a[] to see if all of the elements are the same.
    • Add -1 to v and then return v if they are the same.
  • Create two pointers hi and lo that are initialized to the indices of the highest and lowest elements in the array a[].
  • Set the boolean variable is_hi = true initially to denote that the highest member in a[] will be the first element to be added to v.
  • Run a loop while lo <= hi, check if is_hi == true, add element a[hi] to v and decrement hi by 1, else, add the element pointed by lo to v and increment lo by 1  
    • At the conclusion of each iteration, flip the value of is hi using is_hi ^= true.
  • Return the ArrayList containing the final heights as v.

Below is the implementation of the above approach:

C++




#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
 
vector<int> reaching_height(int n, int a[])
{
    vector<int> v;
    if (n == 1) {
        v.push_back(a[0]);
        return v;
    }
    sort(a, a + n);
    if (a[0] == a[n - 1]) {
        v.push_back(-1);
        return v;
    }
    int hi = n - 1;
    int lo = 0;
    bool is_hi = true;
    while (lo <= hi) {
        if (is_hi) {
            v.push_back(a[hi]);
            hi--;
        }
        else {
            v.push_back(a[lo]);
            lo++;
        }
        is_hi ^= true;
    }
    return v;
}
 
int main()
{
    // Test case 1
    int arr1[] = { 2, 3, 4, 5 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
    vector<int> res1 = reaching_height(n1, arr1);
    for (int i = 0; i < res1.size(); i++) {
        cout << res1[i] << " ";
    }
    return 0;
}


Java




/*package whatever // do not write package name here */
 
import java.util.*;
 
class GFG {
 
    public static ArrayList<Integer>
    reaching_height(int n, int a[])
    {
        ArrayList<Integer> v = new ArrayList<>();
        if (n == 1) {
            v.add(a[0]);
            return v;
        }
        Arrays.sort(a);
        if (a[0] == a[n - 1]) {
            v.add(-1);
            return v;
        }
        int hi = n - 1;
        int lo = 0;
        boolean is_hi = true;
        while (lo <= hi) {
            if (is_hi) {
                v.add(a[hi]);
                hi--;
            }
            else {
                v.add(a[lo]);
                lo++;
            }
            is_hi ^= true;
        }
        return v;
    }
 
    // Drivers code
    public static void main(String[] args)
    {
        // Test case 1
        int[] arr1 = { 2, 3, 4, 5 };
        int n1 = arr1.length;
        ArrayList<Integer> res1 = reaching_height(n1, arr1);
        System.out.println(res1);
    }
}


Javascript




function reaching_height(n, a) {
  let v = [];
  if (n == 1) {
    v.push(a[0]);
    return v;
  }
  a.sort(function(x, y) {
    return x - y;
  });
  if (a[0] == a[n - 1]) {
    v.push(-1);
    return v;
  }
  let hi = n - 1;
  let lo = 0;
  let is_hi = true;
  while (lo <= hi) {
    if (is_hi) {
      v.push(a[hi]);
      hi--;
    } else {
      v.push(a[lo]);
      lo++;
    }
    is_hi = !is_hi;
  }
  return v;
}
 
// Test case 1
let arr1 = [2, 3, 4, 5];
let n1 = arr1.length;
let res1 = reaching_height(n1, arr1);
for (let i = 0; i < res1.length; i++) {
  console.log(res1[i] + " ");
}


C#




// C# code implementation
 
using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
 
    static List<int> reaching_height(int n, int[] a)
    {
        List<int> v = new List<int>();
        if (n == 1) {
            v.Add(a[0]);
            return v;
        }
        Array.Sort(a);
        if (a[0] == a[n - 1]) {
            v.Add(-1);
            return v;
        }
        int hi = n - 1;
        int lo = 0;
        bool is_hi = true;
        while (lo <= hi) {
            if (is_hi) {
                v.Add(a[hi]);
                hi--;
            }
            else {
                v.Add(a[lo]);
                lo++;
            }
            is_hi ^= true;
        }
        return v;
    }
 
    static public void Main()
    {
 
        // Code
        // Test case 1
        int[] arr1 = { 2, 3, 4, 5 };
        int n1 = arr1.Length;
        List<int> res1 = reaching_height(n1, arr1);
        Console.Write("[");
        Console.Write(string.Join(", ", res1));
        Console.Write("]");
    }
}
 
// This code is contributed by lokesh.


Python3




def reaching_height(n, a):
    v = []
    if n == 1:
        v.append(a[0])
        return v
    a.sort()
    if a[0] == a[n-1]:
        v.append(-1)
        return v
    hi = n - 1
    lo = 0
    is_hi = True
    while lo <= hi:
        if is_hi:
            v.append(a[hi])
            hi -= 1
        else:
            v.append(a[lo])
            lo += 1
        is_hi ^= True
    return v
 
 
# Test case 1
arr1 = [2, 3, 4, 5]
res1 = reaching_height(len(arr1), arr1)
for i in range(len(res1)):
    print(res1[i], end=" ")


Output

[5, 2, 4, 3]

Time Complexity: O(N*log(N)).
Auxiliary Space: O(N).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads