Yet Another Array Problem!

On the occasion of Independence Day, Punjab Engineering College decides to conduct a Flag Hoisting Ceremony and decides to give Flag Hoisting opportunity to one of the students. So, they decide to give students an interesting array problem and the student which comes up with the best solution fastest gets the golden opportunity.

Formally, the problem is described below.

You are given an array A with N integers. You can remove an element either from the front or end of the array A and append it to another array B (initially B is empty). You have to simulate this process till there is atleast one element left in A . The task seems pretty easy but isn't. You have to find is there any way to perform the above steps in any order such that the we get B sorted in non-decreasing fashion.

Akshit doesn't want to miss this golden opportunity but since he is a noob in programming, he asks your help to solve this problem for him. Can you solve it for him?

Example:

Input: n=3, arr[] = { 1, 2, 5 }
Output: YES

Approach

Java

public class YetAnotherArrayProblem {

    public static void main(String args[]) {
        int n = 3;
        int arr[] = { 125 };
        String res = ans(n, arr);
        System.out.println(res);
    }

    public static String ans(int nint arr[]) {
        int last = 0;
        int i = 0, j = n - 1;
        while (i != j) {
            if (arr[i] < arr[j] && last <= arr[i]) {
                last = arr[i];
                i++;
            } else if (arr[j] <= arr[i] && last <= arr[j]) {
                last = arr[j];
                j--;
            } else
                return "NO";
        }
        return "YES";
    }
}


No comments:

Post a Comment