算法练习(11) —— Split Array Largest Sum

算法练习(11) —— Split Array Largest Sum

习题

本题取自 leetcode 中的 Dynamic Programming 栏目中的第410题:
Split Array Largest Sum


题目如下:

Description:

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.

Example:

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.

Note

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

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

思路与代码

  • 先理解一下题意,这次的有点绕: 给你两个输入,一个是整数数组nums,另一个是m。将nums分成m个小数组后,求出每个小数组内所有数的和,再在所有和中找到最大值res,作为输出。题目要让我们找到res的最小值。
  • 注意几个点:第一是数组内数字的顺序不能改变,第二是子数组不能为空,至少要有一个数据。
  • 思路的话,很容易就想到动态规划去了,毕竟这种类型的题目很适合动态规划。具体的状态转移方程为:
    // dp[a][b] : a为当前数组的长度, b为剩余切割的次数
    // Xi为切割点
    dp[len][m] = min {max(dp[Xi][m-1], dp[len-Xi][m-1])}
    dp[1][m] = 1
    dp[len][0] = len
  • 自己当时图方便用递归写的,写的挺粗,感觉运行速度有点慢。可以作以下改进:一是记录dp表,如果递归的时候能找到非0值就可以直接返回;二是将递归化为非递归

具体代码如下:

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int split(vector<int>& nums, int m) {
        int len = nums.size();
        if (len == 1)
            return nums[0];
        /*if (len == 2 && m == 1)
            return nums[0] > nums[1] ? nums[0] : nums[1];*/
        if (m == 0) {
            int res = 0;
            for (int i = 0; i < len; i++)
                res += nums[i];
            return res;
        }

        long long result = 9999999999;

        for (int i = 1; i < len; i++) {
            vector<int> left;
            vector<int> right;
            for (int j = 0; j < i; j++)
                left.push_back(nums[j]);
            for (int k = i; k < len; k++)
                right.push_back(nums[k]);
            for (int leftm = 0; leftm <= m - 1; leftm++) {
                int rightm = m - 1 - leftm;
                int l = split(left, leftm);
                int r = split(right, rightm);
                int sum = l > r ? l : r;
                result = (result < sum) ? result : sum;
            }
        }
        return result;
    }

    int splitArray(vector<int>& nums, int m) {
        return split(nums, m - 1);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值