Cloud Stack Ninja

Given an array and a positive integer k, find the first negative integer for each window(contiguous subarray) of size k. If a window does not contain a negative integer, then print 0 for that window.

package com.slidingwindow;

public class demo2 {


    public static void  maximum(int arr[], int k) {
        int index = -1;
        boolean flag = false;

        int i = 0, j = 0, sum = 0;

        while (j < arr.length) {
            
        if(arr[j]<0 && !flag) {
            index =j;
            flag = true;
            System.out.println(arr[index]);
        }
        
            
            if (j - i + 1 < k) {
                j++;
                
            } else if (j - i + 1 == k) {
                
                if(!flag) {
                    System.out.println("0");
                    i++;
                    j++;
                }else {
                    //slide window by incrementing i and j
                    i++;
                    j++;
                    flag = false;a
                }
                
                
            }
        }

    

    }
    public static void main(String[] args) {
        int arr[] = { -2, 5, 1, 8, -2, 9, -1 };
        int k = 2;
        maximum(arr, k);
        

    }

}

Expected output

-2

0

0

-2

-2

-1

Actual

-2

0

0

-2

0

-1



Read more here: https://stackoverflow.com/questions/64406006/first-negative-integer-in-every-window-of-size-k-with-auxiliary-space-o1

Content Attribution

This content was originally published by coder25 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: