An algorithm which check a array and perform operations

Problem

Given an array and an integer number perform the operations to increase or set the max value where if the value of the position is >= 1 and <= N then the operation is to increase, otherwise the operation is to set the max value so far after all return as the result an array with the values of this solution.

Example.

For an input as Integer N = 5 and array A as [2,4,4,6,2,4,4], for each operation it will be as following.

(0, 1, 0, 0, 0)

(0, 1, 0, 1, 0)

(0, 1, 0, 2, 0)

(2, 2, 2, 2, 2)

(2, 3, 2, 2, 2)

(2, 3, 2, 3, 2)

(2, 3, 2, 4, 2)

So, the result of this problem will be [2, 3, 2, 4, 2].

Solution

public boolean isToSum(int value, int N) {
    return value >= 1 && value <= N;
}

public int[] algo(int N, int[] A) {
    int[] res = new int[N];
    int max =0;
    for (int i=0; i < A.length; i++){
        int value = A[i];
        if ( isToSum(value, N)) {
            int sum = res[value-1] +1;
            res[value-1] = sum;
            if (max < sum) {
                max = sum;
            }
        } else {
            Arrays.fill(res, max);
        }
    }
    return res;
}

However, it also can be solved in a more performative way with a Big-O(n+m) as follows.

public boolean isToSum(int value, int N) {
    return value >= 1 && value <= N;
}

public int[] algo(int N, int[] A) {
    int[] res = new int[N];
    int max =0;
    int minValue = 0;

    for (int i=0; i < A.length; i++){
        int value = A[i];
        int pos = value -1;
        if ( isToSum(value, N)) {
            if( res[pos] < minValue) {
                res[pos] = minValue;
            }
            res[pos] += 1;
            if (max < res[pos]) {
                max = res[pos];
            }
        } else {
            minValue = max;
        }
    }

    for (int i=0; i < res.length; i++){
        if ( res[i] < minValue ){
            res[i] = minValue;
        }
    }
    return res;
}

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 )

Facebook photo

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

Connecting to %s