First negative integer in every window of size k with auxiliary space O(1) and O(n) time complexity

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


Solution 1:

I tried to understand your logic, but I couldn't quite get it. Here's what I came up with, starting pretty much from scratch:

class demo2 {

    public static void maximum (int arr[], int k){
        for (int j = 0; j < arr.length - k + 1; j++) {
            boolean found = false;
            for (int x = j; x < j + k; x++) {
                if (arr[x] < 0) {
                    System.out.println(arr[x]);
                    found = true;
                    break;
                }
            }
            if (!found)
                System.out.println(0);
        }
    }

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

Result:

-2
0
0
-2
-2
-1

I recognize that there might be a more efficient way of doing this to the point that it would matter, if both the array length and the window size were significantly large. But your question doesn't state that this is the case. This is a place where you need to be sure you want to spend the time to optimize beyond the simple and obvious solution.