牛客编程巅峰赛S1第6场 - 黄金&钻石&王者 B.牛牛摆放花 (贪心)

  • 题意;将一组数重新排序,使得相邻两个数之间的最大差值最小.

  • 题解:贪心,现将所有数sort一下,然后正向遍历,将数分配到新数组的两端,然后再遍历一次维护一个最大值即可.

  • 代码:

    class Solution {
    public:
        /**
         * ​返回按照这些花排成一个圆的序列中最小的“丑陋度”
         * @param n int整型 花的数量
         * @param array int整型vector 花的高度数组
         * @return int整型
         */
        int cnt[1000000];
        int solve(int n, vector<int>& array) {
            // write code here
            sort(array.begin(),array.end());
            int l=0;
            int r=n+1;
            for(int i=0;i<n;++i){
                if(i%2==0) cnt[++l]=array[i];
                else cnt[--r]=array[i];
            }
            int ans=0;
            for(int i=1;i<n;++i){
                int tmp=abs(cnt[i]-cnt[i+1]);
                ans=max(ans,tmp);
            }
            return ans;
        }
    };
    

猜你喜欢

转载自www.cnblogs.com/lr599909928/p/13380053.html