Longest Peak

package com.vishpat.practice.ds.array;

enum States {
    UNKNOWN,
    ASCENDING,
    DESCENDING
}

public class LongestPeak {
    public static int longestPeak(int[] array) {
        States currentState = States.UNKNOWN;
        States prevState = States.UNKNOWN;
        int longestSize = 0;
        int ascendingStartIdx = -1;
        int descendingEndIdx = -1;

        if (array.length < 3) {
            return 0;
        }

        for (int i = 0; i < array.length - 1; i++) {
            prevState = currentState;

            if (array[i + 1] > array[i]) {
                switch (prevState) {
                    case UNKNOWN:
                        currentState = States.ASCENDING;
                        ascendingStartIdx = i;
                        break;
                    case ASCENDING:
                        currentState = States.ASCENDING;
                        break;
                    case DESCENDING:
                        currentState = States.ASCENDING;
                        ascendingStartIdx = i;
                        break;
                }
            }

            if (array[i + 1] < array[i]) {
                switch (prevState) {
                    case UNKNOWN:
                        currentState = States.DESCENDING;
                        break;
                    case ASCENDING:
                        currentState = States.DESCENDING;
                        descendingEndIdx = i + 1;
                        break;
                    case DESCENDING:
                        currentState = States.DESCENDING;
                        descendingEndIdx = i + 1;
                        break;
                }
            }

            if (ascendingStartIdx >= 0 && descendingEndIdx >= 0 &&
                ascendingStartIdx < descendingEndIdx) {
                int size = descendingEndIdx - ascendingStartIdx + 1;
                if (size > longestSize && size > 2) {
                    longestSize = size;
                }
            }
        }
        return longestSize;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s