查找数组中最大连续整数的问题

问题描述 投票:0回答:1

我正在寻找数组中连续整数的最大数量,使得任意两个整数之间的差小于或等于给定值 K。

以下是我的方法。

// diamonds is an integer array
// N is the length of diamonds
int max = 0;
for(int i = 0; i < N; i++){
        int count = 0;
        for(int j = 0; j < N; j++){
            if(Math.abs(diamonds[i] - diamonds[j]) <= K)){
                count++;
            }
        }
        max = Math.max(max, count);
    }

输出错误答案,但我个人认为我的逻辑是正确的?

官方的解决方案有不同的条件

if(diamonds[i] <= diamonds[j] && diamonds[j] <= diamonds[i] + K){count++;}
,但其余和我的一样。

我不明白这两种条件有什么区别以及为什么我的不起作用。

仅供参考,我在解决这个问题时遇到了这个问题钻石收藏家,但我怀疑我误解了这个问题。

java if-statement conditional-statements
1个回答
0
投票

我相信问题出在你的内部循环。如果您从

i
开始内循环,您将得到正确的答案。

for (int j = i; j < N; j++) {
     if (Math.abs(diamonds[i] - diamonds[j]) <= K) {
          count++;
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.