首页 > 解决方案 > 我不知道为什么我的代码给出了错误的答案

问题描述

给定一个由 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 更改为 1。

返回仅包含 1 的最长(连续)子数组的长度。

示例 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.

示例 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.

笔记:

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

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

这是问题链接。在第一个测试用例中,我得到了输出 9,但它应该是 6。我不知道哪里出了问题?

 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);
}

标签: javaarrays

解决方案


您不需要提供数组的大小,因为您可以从数组中获取大小。如果使用更好的变量名,代码的可读性会更好。此外,您可以使用 if 语句来检查更改的值而不是计数。

这是解决方案的示例:

  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;
  }

推荐阅读