zoukankan      html  css  js  c++  java
  • [Swift]LeetCode410. 分割数组的最大值 | Split Array Largest Sum

    原文地址:https://www.cnblogs.com/strengthen/p/10330269.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:

    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,你需要将这个数组分成 个非空的连续子数组。设计一个算法使得这 个子数组各自和的最大值最小。

    注意:
    数组长度 满足以下条件:

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

    示例:

    输入:
    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 }
  • 相关阅读:
    leetcode401 二进制手表问题
    HashMap与Hashtable
    ideal配置web项目
    java多线程
    spring boot项目启动报错:Failed to load property source from location 'classpath:/application.yml'
    spring cloud实例Dome详细搭建(一)
    ideal激活方法
    Go学习第三章面向对象
    Go学习第二章内建容器
    Go学习第一章基础语法
  • 原文地址:https://www.cnblogs.com/strengthen/p/10330269.html
Copyright © 2011-2022 走看看