[Swift]LeetCode410. 分割數組的最大值 | Split Array Largest Sum

原文地址:http://www.javashuo.com/article/p-ezklopcy-dc.html html

Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays.算法

Note:
If n is the length of array, assume the following constraints are satisfied:數組

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ min(50, n

Examples:spa

Input:
nums = [7,2,5,10,8]
m = 2

Output:
18

Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

給定一個非負整數數組和一個整數 m,你須要將這個數組分紅 個非空的連續子數組。設計一個算法使得這 個子數組各自和的最大值最小。設計

注意:
數組長度 知足如下條件:code

  • 1 ≤ n ≤ 1000
  • 1 ≤ m ≤ min(50, n)

示例:htm

輸入:
nums = [7,2,5,10,8]
m = 2

輸出:
18

解釋:
一共有四種方法將nums分割爲2個子數組。
其中最好的方式是將其分爲[7,2,5] 和 [10,8],
由於此時這兩個子數組各自的和的最大值爲18,在全部狀況中最小。

12ms
 1 class Solution {
 2     func splitArray(_ nums: [Int], _ m: Int) -> Int {
 3         var nums = nums
 4         var left:Int = 0
 5         var right:Int = 0
 6         for i in 0..<nums.count
 7         {
 8             left = max(left, nums[i])
 9             right += nums[i]
10         }
11         while (left < right)
12         {
13             var mid:Int = left + (right - left) / 2
14             if canSplit(&nums, m, mid)
15             {
16                 right = mid
17             }
18             else
19             {
20                 left = mid + 1
21             }
22         }
23         return left
24     }
25     
26     func canSplit(_ nums:inout [Int], _ m: Int, _ sum: Int) -> Bool
27     {
28         var cnt:Int = 1
29         var curSum:Int = 0
30         for i in 0..<nums.count
31         {
32             curSum += nums[i]
33             if curSum > sum
34             {
35                 curSum = nums[i]
36                 cnt += 1
37                 if cnt > m
38                 {
39                     return false
40                 }
41             }
42         }
43         return true
44     }
45 }
相關文章
相關標籤/搜索