算法编程(Java)#奖品数量

版权声明:作者:xp_9512 来源:CSDN 版权声明:本文为博主原创文章,转载请附上博文链接! 原文: https://blog.csdn.net/qq_40981804/article/details/89530839

题目

有n个人参加编程比赛,比赛结束后每个人都有一个分数
现在所有人排成一个圈(第1个人和第n个人相邻)领取奖品,要求满足:

  • 如果一个人比他相邻的人的分数高,那么他获得的奖品应该要多余相邻的人
  • 每个人至少需要得到一个奖品

输入描述

输入描述:
第一行是一个整数t,表示测试样例的个数
每个测试样例的第一行是一个正整数n,表示参加比赛的人数(0 < n < 100000)
第二行是n个整数a[i],表示每个人的分数(0 < a[i] < 100000)
输出描述:
对每个测试样例,输出应该准备的最少奖品数
示例1
输入:
2
2
1 2
4
1 2 3 3
输出:
3
8

解题思路

首先从左往右遍历,如果后面的数大于前面的,奖品数+1,否则奖品数=1,这样确保可每个人都至少有一个奖品。

再从右往左遍历,如果后面的数小于前面的数,这时,如果前面的奖品大于后面,继续判断,否则,前面的奖品数得变为Math.max(award[i],award[i+1]+1)。

答案

public class test3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        //测试样例个数
        int n = sc.nextInt();
        //存结果
        ArrayList<Integer> res = new ArrayList<Integer>();
        while (n-- != 0) {
            //人数
            int people = sc.nextInt();
            int[] score = new int[people+1];
            //保存分数
            for (int i = 0; i < people; i++) {
                score[i] = sc.nextInt();
            }
            score[people] = score[0];
            int res1 = countAward(score);
            res.add(res1);
        }
        for (Integer i :res)
            System.out.println(i);
    }
 
    private static int countAward(int[] score) {
        int res1 = 0;
        int[] award = new int[score.length];
        score[0] = 1;
        award[0] = 1;
        //先从左往右遍历,满足了每个人都至少有一个奖品
        for (int i = 1; i < score.length; i++) {
            if (score[i] > score[i - 1])
                award[i] = award[i - 1] + 1;
            else
                award[i] = 1;
        }
        //再从右往左遍历
        for (int i = score.length - 2; i > -1; i--) {
            if (score[i]> score[i+1]) {
                if (award[i] > award[i+1])
                    continue;
                else
                    award[i] = Math.max(award[i],award[i+1]+1);
            }
        }
        for (int i = 0; i < award.length-1; i++) {
            res1 += award[i];
        }
        return res1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40981804/article/details/89530839