Sunday, March 17, 2024

 

Given a non-empty array of N integers describing elevation along x-axis starting at 0 and  defining peaks as co-ordinates where the elevation is greater than adjacents, find the maximum number of flags that can be put on peaks such that the distance between any two co-ordinates is no less than K.

    public static boolean[] getPeaks(int[] A) {

        boolean[] peaks = new boolean[A.length];

        for (int i = 1; i < A.length-1; i++) {

            if (A[i] > A[i-1] && A[i] > A[i+1]) {

                peaks[i] = true;

            } else {

                peaks[i] = false;

            }

        }

        return peaks;

    }

    public static int[] nextPeaks(int[] A) {

        int[] next = new int[A.length];

        boolean[] peaks = getPeaks(A);

        next[A.length-1] = -1;

        if (peaks[A.length-1]) next[A.length-1] = A.length-1;

        for (int i = next.length-2; i >= 0; i--) {

             if (peaks[i]) {

                 next[i] = i;

             } else {

                 next[i] = next[i+1];

             }

        }

        return next;

    }

    public static int countMaxFlagsOnPeaks(int[] A, int K) {

        int[] next = nextPeaks(A);

        int i = 1;

        int result = 0;

        for (int I =0; I < A.length; i++)

            int pos = i;

            int num = 0;

            while (pos < A.length && num < i) {

                int n = next[pos];

                if (n == -1) {

                    break;

                }

               If (n == pos && pos + 1 < next.length && next[pos+1] != -1 && next[pos+1] – pos  >=K) {

                num += 1;

               }

               // if bidirectional

               // If (n == pos && pos -1 >= 0 && pos - next[pos-1]  >= K) {

                // num +=1;

               // }

                pos = next[pos+1];

            }

            result = Math.max(result, num);

            System.out.println("i=" + i + " num=" + num + " result=" + result);

            // i+=1;

        }

        return result;

    }

A:          1,5,3,4,3,4,  1,  2,  3,  4,  6,  2

K:           1

peaks:0,1,0,1,0,1,  0,  0,  0,  0,  1,  0

next:    1,1,3,3,5,5,10,10,10,10,10,-1

i=1 num=3 result=3

i=3 num=3 result=3

i=5 num=3 result=3

i=10 num=3 result=3

3

 

No comments:

Post a Comment