MinMaxDivision

https://app.codility.com/programmers/lessons/14-binary_search_algorithm/min_max_division/

You are given integers K, M and a non-empty array A consisting of N integers. Every element of the array is not greater than M.

You should divide this array into K blocks of consecutive elements. The size of the block is any integer between 0 and N. Every element of the array should belong to some block.

The sum of the block from X to Y equals A[X] + A[X + 1] + ... + A[Y]. The sum of empty block equals 0.

The large sum is the maximal sum of any block.

For example, you are given integers K = 3, M = 5 and array A such that:

A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2 A[6] = 2

The array can be divided, for example, into the following blocks:

  • [2, 1, 5, 1, 2, 2, 2], [], [] with a large sum of 15;
  • [2], [1, 5, 1, 2], [2, 2] with a large sum of 9;
  • [2, 1, 5], [], [1, 2, 2, 2] with a large sum of 8;
  • [2, 1], [5, 1], [2, 2, 2] with a large sum of 6.

The goal is to minimize the large sum. In the above example, 6 is the minimal large sum.

Write a function:

class Solution { public int solution(int K, int M, int[] A); }

that, given integers K, M and a non-empty array A consisting of N integers, returns the minimal large sum.

For example, given K = 3, M = 5 and array A such that:

A[0] = 2 A[1] = 1 A[2] = 5 A[3] = 1 A[4] = 2 A[5] = 2 A[6] = 2

the function should return 6, as explained above.

Write an efficient algorithm for the following assumptions:

  • N and K are integers within the range [1..100,000];
  • M is an integer within the range [0..10,000];
  • each element of array A is an integer within the range [0..M].

思路:二分

# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def ok(A,mid,K):
    i=0
    for _ in range(K-1):
        s=0
        while i<len(A) and s+A[i]<=mid:
            s+=A[i]
            i+=1
    return sum(A[i:])<=mid
    

def solution(K, M, A):
    # write your code in Python 3.6
    su=sum(A)
    mi=su//K if su%K==0 else su//K+1
    mi=max(mi, max(A))
    
    i=ma=0
    for _ in range(K-1):
        s=0
        while i<len(A) and s+A[i]<=mi: 
            s+=A[i]
            i+=1
        ma=max(ma,s)
    ma=max(ma, sum(A[i:]))
    
    res=sum(A)
    while mi<=ma:
        mid=(mi+ma)//2
        if ok(A,mid,K):
            res=min(res,mid)
            ma=mid-1
        else:
            mi=mid+1
    return res

#print(solution(3, 5, [2, 1, 5, 1, 2, 2, 2]))
print(solution(3, 20, [3,4,3,4,16]))
            
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值