约翰的生意

http://www.lintcode.com/zh-cn/problem/johns-business/#

public class Solution {
    /**
     * @param A: The prices [i]
     * @param k:
     * @return: The ans array
     */
    public int[] business(int[] A, int k) {
        // Write your code here
        int[] res = new int[A.length];
        Node root = build(A, 0, A.length - 1);
        for (int i = 0; i < A.length; i++) {
            int left = i - k;
            int right = i + k;
            left = Math.max(left, 0);
            right = Math.min(A.length - 1, right);
            int min = query(root, left, right);
            res[i] = A[i] - min;
        }
        return res;
    }

    private int query(Node root, int left, int right) {
        if (left <= root.start && right >= root.end) {
            return root.min;
        }
        int res = Integer.MAX_VALUE;
        int mid = (root.start + root.end) / 2;

        if (left <= mid) {
            res = Math.min(res, query(root.left, left, right));
        }
        if (right > mid) {
            res = Math.min(res, query(root.right,left, right));
        }
        return res;
    }

    private Node build(int[] a, int i, int j) {
        if (i > j) {
            return null;
        }
        if (i == j) {
            return new Node(i, j, a[i]);
        }

        int mid = (i + j) / 2;
        Node root = new Node(i, j, Integer.MAX_VALUE);

        root.left = build(a, i, mid);
        root.right = build(a, mid + 1, j);

        if (root.left != null) {
            root.min = Math.min(root.min, root.left.min);
        }
        if (root.right != null) {
            root.min = Math.min(root.min, root.right.min);
        }
        return root;
    }


    private class Node {
        int start;
        int end;
        int min;
        Node left;
        Node right;

        public Node(int start, int end, int min) {
            this.start = start;
            this.end = end;
            this.min = min;
        }
    }

}

你可能感兴趣的:(约翰的生意)