|
| 1 | +// Given an array nums which consists of non-negative integers and an integer m, |
| 2 | +// you can split the array into m non-empty continuous subarrays. |
| 3 | +// Input: nums = [7,2,5,10,8], m = 2 |
| 4 | +// Output: 18 |
| 5 | +// Explanation: |
| 6 | +// There are four ways to split nums into two subarrays. |
| 7 | +// The best way is to split it into [7,2,5] and [10,8], |
| 8 | +// where the largest sum among the two subarrays is only 18. |
| 9 | + |
| 10 | +#include<bits/stdc++.h> |
| 11 | +using namespace std; |
| 12 | + |
| 13 | +int splitArray(vector<int>& nums, int m) { |
| 14 | + int n = nums.size(); |
| 15 | + vector<vector<int>> dp(n + 1, vector<int>(m + 1, INT_MAX)); |
| 16 | + vector<int> sub(n + 1, 0); |
| 17 | + for (int i = 0; i < n; i++) { |
| 18 | + sub[i + 1] = sub[i] + nums[i]; |
| 19 | + } |
| 20 | + // f[i][j] to be the minimum largest subarray sum for splitting nums[0..i] into j parts |
| 21 | + dp[0][0] = 0; |
| 22 | + for (int i = 1; i <= n; i++) { |
| 23 | + for (int j = 1; j <= m; j++) { |
| 24 | + for (int k = 0; k < i; k++) { |
| 25 | + dp[i][j] = min(dp[i][j], max(dp[k][j - 1], sub[i] - sub[k])); |
| 26 | + } |
| 27 | + } |
| 28 | + } |
| 29 | + return dp[n][m]; |
| 30 | +} |
| 31 | + |
| 32 | +int main(){ |
| 33 | + // Number of element in the array |
| 34 | + int n; |
| 35 | + cin >> n; |
| 36 | + vector<int> nums(n); |
| 37 | + // Input element of an array |
| 38 | + for(int i = 0; i < n; i++){ |
| 39 | + cin >> nums[i]; |
| 40 | + } |
| 41 | + |
| 42 | + int number_of_split; |
| 43 | + cin >> number_of_split; |
| 44 | + // calling splitArray function to find number of ways to split nums into number_of_split subarray |
| 45 | + // with minimum largest sum. |
| 46 | + cout << splitArray(nums, number_of_split) << endl; |
| 47 | + |
| 48 | + return 0; |
| 49 | +} |
| 50 | + |
| 51 | +// Input 1: nums = [7,2,5,10,8], number_of_split = 2 |
| 52 | +// Output 1: 18 |
| 53 | + |
| 54 | +// Input 2: nums = [1,2,3,4,5], number_of_split = 2 |
| 55 | +// Output 2: 9 |
| 56 | + |
| 57 | +// Input: nums = [1,4,4], number_of_split = 3 |
| 58 | +// Output: 4 |
| 59 | + |
| 60 | +// Time Complexity : O(n * n + number_of_split) |
| 61 | +// Space Complexity : O(n * number_of_split) |
| 62 | +// where n is the size of array nums. |
0 commit comments