I don't know why my code is giving wrong answer

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:

Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation: 
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Example 2:

Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation: 
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.

Note:

1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1 

https://leetcode.com/problems/max-consecutive-ones-iii/

This is the question link. On the first test case, I am getting output 9 but it should be 6. I can't figure out where it is going wrong?

 public static int f(int arr[],int n,int tar)
 {
   
    int st=0,maxc=0,maxf=0;
    //tar=tar+1;
    for(int i=0;i<n;i++)
    {
        int se=i-st-maxc;
        if(arr[i]==1)
       maxc++;
        while(i-st-maxc>tar)
        {
            maxf=Math.max(maxf, i-st);
            st++;
        }
       
    }
    return maxf+1;
}
public static void main(String[] args)
{
    Scanner p=new Scanner(System.in);
    int n,target;
    n=p.nextInt();
    target=p.nextInt();
    int arr[]=new int[n];
    for(int i=0;i<n;i++)
    {
        arr[i]=p.nextInt();
    }
    int ans=f(arr,n,target);
    System.out.println(ans);
}

Upvotes: 0

Views: 110

Answers (1)

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2900

You do not need to provide the size of the array because you can get the size from the array. If you use better variable names, the readability of the code will be better. Also, you can use if statements in order to check changed values instead of counting.

This is example of the solution:

  public static int longestOnes(int[] A, int K) {
    var maxCount = 0;
    for (int i = 0; i < A.length; i++) {
      var count = 0;
      var k = 0;
      for (int j = i; j < A.length; j++) {
        if (A[j] == 1) {
          count++;
        }
        if (A[j] == 0) {
          if (k >= K) {
            if (count > maxCount) {
              maxCount = count;
            }
            break;
          }
          count++;
          k++;
        }
      }
    }
    return maxCount;
  }

Upvotes: 1

Related Questions