//prefix sum - o(n) - do not need. calculate immediately //dp from - to o(n^2 * m) //select minimum //1 ... 1000 length //0 ... 1000000 nums classSolution { int dp[1001][50]; intsolution(vector<int>& nums, int l, int m){ if(dp[l][m] != -1) return dp[l][m]; //if already calculated if(!m) return dp[l][m] = accumulate(nums.begin() + l, nums.end(), 0); //do not need to devide, so add all int res = INT_MAX, sum = 0; //init for(int i = l; i < nums.size() - m; i++) { sum += nums[i]; res = min(res,max(sum,solution(nums, i + 1, m - 1))); //compare minimum max value before and current max value } return dp[l][m] = res; } public: intsplitArray(vector<int>& nums, int m){ memset(dp,-1,sizeof(dp)); returnsolution(nums,0,m-1); } };