Java 最大对数

Java 最大对数,java,arrays,algorithm,Java,Arrays,Algorithm,我需要找出通过改变给定数组中的单个数字就可以找到的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对的最大数目

例如:

如果我的输入是
{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;
    }
}
公共类程序{
公共静态void main(字符串[]args){
程序=新程序();
int[]a={1,0,0,1,0,1};
int响应=程序计算(a);
System.out.println(响应);
}
int计算(int[]输入){
if(input==null | | input.length==0){
返回-1;
}
int length=input.length;
int结果=0;
对于(int i=0;i0){
如果(输入[i-1]!=输入[i]){
计数=计数+1;
}否则{
计数=计数-1;
}
}
如果(i<长度-1){
如果(输入[i+1]!=输入[i]){
计数=计数+1;
}否则{
计数=计数-1;
}
}
温度=数学最大值(温度、计数);
}
返回结果+温度;
}
}

我被告知程序有一些错误,但我无法找出问题所在。我尝试将各种值传递给这个程序,但它仍然可以正常工作。你能帮我解决一下这个程序失败的输入组合吗。

嗯,它似乎失败了

{ 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 

似乎是最大子阵列问题。卡丹的算法应该提供一个答案。int[]a={1,0,0,0,0,1,0,0,1,0,0,0};->获得8分answer@RajeevRanjan,最大子数组不同,与我的问题无关。8的答案是正确的,因为如果我替换位置7,那么我们得到8对OK。。我在寻找最长的序列。。谢谢