大学算法题代码错误排查:寻找最大对比度图像对
算法题代码错误排查
题目要求
知名艺术家Ignat连续N天每天画一幅画,第i天的画亮度为ai。需找出对比度最大的画对(i,j),即ai−aj的值为所有可能对中的最大值;若存在多组这样的对,需选择i−j最大的那组,且(i,j)与(j,i)视为不同对。
输入要求:第一行输入整数N(天数),第二行输入N个整数a1到aN(每天画的亮度)。
输出要求:输出1到N之间的两个不同整数i和j,代表对应天数。
输入示例1:
6
1 2 1 3 1 3
输出示例1:6 1输入示例2:
4
2 1 0 -1
输出示例2:1 4
用户提供的C#代码
int n = int.Parse(Console.ReadLine()); int[] a = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int maxIndex = 0, minIndex = 0; for (int i = 1; i < n; i++) { if (a[i] > a[maxIndex]) { maxIndex = i; } if (a[i] < a[minIndex]) { minIndex = i; } } if (maxIndex < minIndex) { Console.WriteLine((maxIndex + 1) + " " + (minIndex + 1)); } else { Console.WriteLine((minIndex + 1) + " " + (maxIndex + 1)); }
错误分析
你的代码存在两个核心问题:
- 逻辑完全颠倒:题目要求的是找到使
ai - aj最大的对(i,j),也就是需要找到最大的ai和最小的aj,此时对应的输出应该是(最大ai的索引+1) (最小aj的索引+1),但你的代码最后判断后输出的逻辑搞反了。比如示例1中最大ai是索引5(值3),最小aj是索引0(值1),正确输出是6 1,但你的代码会因为maxIndex(5) > minIndex(0),执行else分支输出minIndex+1 maxIndex+1也就是1 6,完全错误。 - 输出逻辑冗余且错误:不需要判断maxIndex和minIndex的大小,题目要求的是
ai - aj最大,无论max和min的位置如何,直接输出最大值的位置和最小值的位置即可,这才是符合要求的结果。
修正后的代码
int n = int.Parse(Console.ReadLine()); int[] a = Array.ConvertAll(Console.ReadLine().Split(), int.Parse); int maxIndex = 0, minIndex = 0; for (int i = 1; i < n; i++) { // 遇到更大的值更新最大值索引,相等时保留更靠后的索引(保证i尽可能大,i-j更大) if (a[i] > a[maxIndex]) { maxIndex = i; } // 遇到更小的值更新最小值索引,相等时保留更靠前的索引(保证j尽可能小,i-j更大) if (a[i] < a[minIndex]) { minIndex = i; } } // 直接输出最大值位置和最小值位置,满足ai-aj最大且i-j最大的要求 Console.WriteLine($"{maxIndex + 1} {minIndex + 1}");
验证示例
- 输入示例1:处理后maxIndex=5,minIndex=0,输出6 1,符合要求。
- 输入示例2:maxIndex=0,minIndex=3,输出1 4,符合要求。
内容的提问来源于stack exchange,提问作者rinyasuperstar
相关产品推荐
相关产品推荐

