中级农民
- 积分
- 151
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-12-3
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
最大化连续子串最小sum (LC 410)
有一个数组,分成K部分,要求, min of subarray sum is maximized, [1,2,4,3,3] 分成3部分, 你可以分成 1| 2,4|3,3 最小数组 是1, 但是你分成 1,2 |4|3,3 最小的数组sum就变成了3. 3是想要的答案。 这个我提出了DP和recursive, 面试官都不满意, 最后用的是二分查找. 比如说你给 一个数 N , 看这个数组能不能被分成K部分, 每个部分都大于N, 如果不能,就试试N/2。
看G家面经 发现这道 LC410 变种, 请大家帮看看我的解法是否正确
- class Solution(object):
- def splitArray(self, nums, m):
- """
- :type nums: List[int]
- :type m: int
- :rtype: int
- """
- def canDivideToM(target, nums, m):
- '''
- if we can divide nums to more than m subarray with target as sum
- for each subarray, it means the target is too small, if we can't mean target is too big
- '''
- count=1
- total=0
-
- for num in nums:
- total+=num
- if total>=target:
- total=0
- count+=1
-
- if count > m:
- return True
- return False
-
-
- #low bound
- left= minNum = min(nums)
- #high bound
- right = sumNums = sum(nums)
-
- # Binary search Template
- while left<=right:
- mid = (left+right)/2
-
- if canDivideToM(mid, nums, m):
- left=mid+1
- else:
- right=mid-1
- return right
-
-
-
复制代码
|
上一篇: 5.2 Facebook 跪经下一篇: 编程之法:面试和算法心得
|