[LintCode] Copy Books

public int copyBooks(int[] pages, int k) {
        // write your code here
        int l = 0;
        int r = 9999999;
        while( l <= r){
            int mid = l + (r - l) / 2;
            if(search(mid,pages,k))
                r = mid-1;
            else
                l = mid+1;
        }
        return l;
    }
    public boolean search(int total, int[] page, int k) {
        int count = 0;
        int sum = 0;
        for(int i = 0; i < page.length;) {
            if(sum + page[i] <= total)
                sum += page[i++];
            else if(page[i] <= total){
                sum = 0;
                count++;
            }
            else
                return false;
        }
        if(sum != 0)
            count++;
        return count <= k;