java - 我不知道为什么我的代码给出了错误的答案
问题描述
给定一个由 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);
}
解决方案
您不需要提供数组的大小,因为您可以从数组中获取大小。如果使用更好的变量名,代码的可读性会更好。此外,您可以使用 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;
}
推荐阅读
- c - 从c中的文本文件中读取图形值
- 3d - Paraview中液滴的表面积计算
- azure-sql-database - Azure Cosmos DB SQL 消耗更多 RU
- python - Python DataFrame:使用映射分解一列
- pine-script - 如何减少脚本编译计数。“编译的脚本代码太长”
- pytorch - 如何通过参数更改在 PyTorch 中恢复优化器
- r - Synth dataprep() Error unit.variable not found as numeric variable in foo 的另一个问题
- azure - az vmss run-command 在运行时是否在所有实例中同时运行?
- javascript - Writing an API response to a separate file
- amazon-web-services - 每当在 Laravel AWS 管道中推送新版本时,我的环境就会被删除