题解 | 元素方碑

元素方碑

https://www.nowcoder.com/practice/5c6e7ed4726e41f4ac99a4dedf1e5bb2

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();
        String [] ans = new String[t];
        for(int i = 0 ; i < t ; i++){
            int n = in.nextInt();
            int [] arr = new int [n];
            int sum = 0;
            for(int j = 0 ; j < n ; j++){
                arr[j] = in.nextInt();
                sum+= arr[j];
            }
            if(n == 1){
                ans[i] = "YES";
                continue;
            }else if(n == 2){
                ans[i] = arr[0] == arr[1] ? "YES" : "NO";
                continue;
            }else if(sum % n != 0){
                ans[i] = "NO";
                continue;
            }
            int target = sum / n;
            boolean flag = false;
            for(int j = 1 ; j < n - 1 ; j++){
                if(arr[j - 1] > target){
                    int num = arr[j - 1] - target;
                   arr[j - 1] -= num;
                   arr[j + 1] += num; 
                }else if(arr[j - 1] < target){
                    int num = target - arr[j - 1];
                   arr[j - 1] += num;
                   arr[j + 1] -= num;
                }
                if(arr[j - 1] < 0 || arr[j + 1] < 0){
                   flag = true; 
                   break;
                }
            }
            if(flag ) ans[i] = "NO";
            else  {
                for(int j = 0 ; j < n - 1; j++){
                    if(arr[j] != arr[j + 1]){
                        flag = true;
                        break;
                    }
                }
               if(flag)  ans[i] = "NO";
               else ans[i] = "YES";
            }
        }
        for(String a : ans){
            System.out.println(a);
        }
    }
}

全部评论

相关推荐

零OFFER战士:另一个版本查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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