You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Codechef提交代码返回WA,求排查三数取两数最大和的错误用例

问题排查与修正

问题根源

你的最小值判断逻辑仅覆盖了单个数值严格小于另外两个数值的场景,当存在多个相等的最小值时(比如两个数同为最小值、三个数全相等),代码无法正确识别出最小值,导致最终计算错误。

举个反例:输入3 1 1

  • 初始min被设为A=3
  • 判断B<A && B<C:1<3成立,但1<1不成立,条件不触发
  • 判断C<A && C<B:1<3成立,但1<1不成立,条件不触发
  • 最终min仍为3,总和3+1+1=5减去3得到2,但正确的最大两数和应为3+1=4,结果错误。

修正方案

方案1:用Math.min正确获取最小值

利用Java内置的Math.min嵌套调用,可以准确获取三个数中的最小值,无需手动判断边界情况:

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        while (T-->0)
        {
            int A=sc.nextInt();
            int B=sc.nextInt();
            int C=sc.nextInt();
            int min = Math.min(A, Math.min(B, C));
            int maxSum = A+B+C - min;
            System.out.println(maxSum);
        }
    }
}

方案2:直接计算所有两两组合的和取最大值

逻辑更直观,完全避免最小值判断的潜在问题:

import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        while (T-->0)
        {
            int A=sc.nextInt();
            int B=sc.nextInt();
            int C=sc.nextInt();
            int sumAB = A+B;
            int sumAC = A+C;
            int sumBC = B+C;
            int maxSum = Math.max(sumAB, Math.max(sumAC, sumBC));
            System.out.println(maxSum);
        }
    }
}

内容的提问来源于stack exchange,提问作者YoAllTheseStacks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:24:28