我需要通过仅更改给定数组中的单个数字来找出 1 和 0 的最大对数。
例如:
如果我的输入是{1,0,0,1,0,0}
,这里在索引位置3
如果我替换1
使用 0
然后我将得到 4 对,即数组变为 {1,0,0,0,0,0}
,并且对是 (1,2) , (2,3), (3,4), (4,5)。
但是如果我将索引位置 0
从 1
替换为 0
那么数组是 {0,0,0,1 ,0,0}
这里我只会得到 3 对,即 (0,1), (1,2), (4,5)
我需要一个程序来返回给定输入数组可能的最大对数。在这种情况下,程序应该给出 4 作为结果。
这里的数组只包含 1 和 0。
这是我的程序:
public class Program {
public static void main(String[] args) {
Program program = new Program();
int[] a = { 1, 0, 0, 1, 0, 1 };
int response = program.calculate(a);
System.out.println(response);
}
int calculate(int[] input) {
if(input == null || input.length == 0) {
return -1;
}
int length = input.length;
int result = 0;
for (int i = 0; i < length - 1; i++) {
if (input[i] == input[i + 1]) {
result = result + 1;
}
}
int temp = 0;
for (int i = 0; i < length - 1; i++) {
int count = 0;
if (i > 0) {
if (input[i - 1] != input[i]) {
count = count + 1;
} else {
count = count - 1;
}
}
if (i < length - 1) {
if (input[i + 1] != input[i]) {
count = count + 1;
} else {
count = count - 1;
}
}
temp = Math.max(temp, count);
}
return result + temp;
}
}
我被告知该程序存在一些错误,但我无法找出问题出在哪里。我尝试将各种值传递给该程序,但它仍然可以正常工作。你能帮我解决这个程序失败的一些输入组合吗?
最佳答案
好吧,它似乎失败了
{ 0, 0, 0, 0, 0, 0, 1}; -> 5 but not {0, 1}; -> 1
{ 1, 0, 1}; -> 2
{ 1, 1, 1}; -> 2
{ 1,0,0,0,0,1,1,0,0,0}; -> 7
关于java - 最大对数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993104/