题解 | #合唱队#

合唱队

http://www.nowcoder.com/practice/6d9d69e3898f45169a441632b325c7b4

动态规划+二分

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();
            int nums[] = new int[n];
            for(int i = 0; i < n;i++) {
                nums[i] = sc.nextInt();
            }
            int out = singQueue(nums, n);
            System.out.println(out);
        }
    }

    public static int singQueue(int[] nums, int n) {
        int[] left = new int[n];
        int[] right = new int[n];
        List<Integer> dp = new ArrayList<>();
        for(int i = 0; i < n; i++) {
            if(dp.isEmpty() || nums[i] > dp.get(dp.size()-1)) {
                dp.add(nums[i]);
                left[i] = dp.size();
            }else if(nums[i] <= dp.get(dp.size()-1)){
                int pos = lowerBound(dp, nums[i]);
                dp.set(pos, nums[i]);
                left[i] = pos + 1;
            }
        }
        dp.clear();
        for(int i = n-1; i >= 0; i--) {
            if(dp.isEmpty() || nums[i] > dp.get(dp.size()-1)) {
                dp.add(nums[i]);
                right[i] = dp.size();
            }else if(nums[i] <= dp.get(dp.size()-1)){
                int pos = lowerBound(dp, nums[i]);
                dp.set(pos, nums[i]);
                right[i] = pos + 1;
            }
        }
        int max = 0;
        for(int i = 0; i<n;i++) {
            max= Math.max(left[i] + right[i], max);
        }
        return n - max + 1;

    }

    public static int lowerBound(List<Integer> dp, int key) {
        int l = 0, r = dp.size() - 1;
        while(l  < r) {
            int mid = (l + r) / 2;
            if(key <= dp.get(mid)) {
                r = mid;
            }else {
                l = l + 1;
            }
        }
        return r;
    }
}
全部评论

相关推荐

10-17 16:07
门头沟学院 Java
牛牛大你18号:在汇报,突然弹出来,,领导以为我在准备跳槽,刚从领导办公室谈心出来
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务