卖票

题目:

有N个售票处,用一个N个元素的数组表示每个售票处剩余的票数,如N = 5, int[] numberOfTicketsRemain = {2, 3, 2, 5, 1}。其中某窗口当期票的价格等于该窗口当前所剩票的个数,如0号窗口目前剩两张票,则price[0][cur] = 2,如果0号窗口卖掉一张票,则还剩一张那么新的price[0][cur] = 1。给定总共要卖掉M张票。问最大收益。


public class Solution {
    public static void main(String args[] ) throws Exception {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] numberOfTickets = new int[n];
        int maximum = 0;
        for(int i = 0; i < n; i++) {
            numberOfTickets[i] = sc.nextInt();
            if(numberOfTickets[i] > maximum)
                maximum = numberOfTickets[i];
        }
        int low = 0, high = maximum;

        while(low + 1 < high) {
            int mid = (low + high) / 2;
            if(countTickets(mid, numberOfTickets) >= m)
                low = mid;
            else
                high = mid;
        }
        
        int value = 0;

        for(int i : numberOfTickets) {
            if(i > high) {
                //sum of arithmetic series
                value += (high + 1 + i) * (i - high) / 2;
            }
        }

        value += (m - countTickets(high, numberOfTickets)) * high;
        System.out.println(value);
    }
    
    private static int countTickets(int lowerBound, int[] numberOfTickets) {
        int count = 0;
        for(int i : numberOfTickets) {
            if(i > lowerBound)
                count += (i - lowerBound);
        }
        return count;
    }
}

你可能感兴趣的:(算法,algorithm,面试题)