题解 | #游游的元素修改#

游游的元素修改

https://www.nowcoder.com/practice/2e3557c96138444db7eca60e8afaaac7

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        int t = in.nextInt();

        while(t > 0){
            t--;
            int n = in.nextInt();
            long lValue = in.nextLong();
            long rValue = in.nextLong();

            long lCount = 0;
            long lNum = 0;
            long rCount = 0;
            long rNum = 0;
            long toLCount = 0;
            long toRCount = 0;
            for(int i = 0;i<n;i++){
                long value = in.nextLong();
                if(value < lValue){
                    lCount += lValue - value;
                    lNum++;
                }else if(value > rValue){
                    rCount += value - rValue;
                    rNum++;
                }else{
                    toLCount += value - lValue;
                    toRCount += rValue - value;
                }
            }

            if(lCount == rCount){
                System.out.println(lCount);
                continue;
            }

            if(lCount > rCount){
                long res = lCount;
                lCount -= rCount;
                toLCount += (rValue - lValue)*rNum;

                if(toLCount >= lCount){
                    System.out.println(res);
                }else{
                    System.out.println(-1);
                }
            }else{
                long res = rCount;
                rCount -= lCount;
                toRCount += (rValue - lValue)*lNum;
                if(toRCount >= rCount){
                    System.out.println(res);
                }else{
                    System.out.println(-1);
                }
            }

        }
    }
}

全部评论

相关推荐

07-22 11:53
门头沟学院 Java
终于有一个保底的offer了,但感觉是白菜价
北凝a:我想问问,提前批的offer 有问你啥时候到岗吗,如果你还想找其他的怎么办
点赞 评论 收藏
分享
07-24 16:39
已编辑
门头沟学院 测试开发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务