Advertisement
SalmaYasser

Untitled

Jan 20th, 2020
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. The idea is that you have to express optimal solution to
  2. current problem through optimal solutions to (overlapping) subproblems.
  3.  
  4. I think, it's better to start with a simple
  5. example for nums=[1, 2, 3, 4, 5] and m=3.
  6. The optimal solution for this problem is
  7. minimum among solutions that include all possible nums prefixes, starting with index 0.
  8.  
  9. best([1, 2, 3, 4, 5], 3) is a min(
  10. max(1, best([2, 3, 4, 5], 2),
  11. max(1 + 2, best([3, 4, 5], 2),
  12. max(1 + 2 + 3, best([4, 5], 2),
  13. )
  14. We see the recursive structure clearly here. Expressed more formally:
  15.  
  16. best(nums, m) is a min(
  17. max(sum(nums[:i]), best(nums[i:], m-1))
  18. for i in range(len(len(nums)-m))
  19. )
  20. I leave it to you to understand,
  21. where subproblems overlap here (multiple calls made with same arguments).
  22.  
  23. Back to complexity.
  24. If we remove caching (memoization) implemented through use of visited,
  25. then we get exponential complexity O(N^N).
  26. With memoization complexity analysis becomes tricky.
  27. But we can get a hint from our cache (visited) dimensions,
  28. that may have at most len(nums) * m unique entries.
  29. This value corresponds to a number of unique subproblems
  30. that have to be solved to get final answer.
  31. Thereby I would say the complexity is O(len(nums) * m) ( O(N * m))
  32.  
  33. long long fun (vector<int>& nums, int idx , int m, vector < vector <int> > &dp)
  34. {
  35. if (dp[idx][m] != -1)
  36. {
  37. return dp[idx][m];
  38. }
  39.  
  40. long long sum = 0;
  41. long long res = INT_MAX;
  42.  
  43. if (m == 0)
  44. {
  45.  
  46. for (int i = idx ; i < nums.size(); i++)
  47. {
  48. sum += nums[i];
  49. }
  50.  
  51. return sum;
  52. }
  53.  
  54. for (int i = idx ; i < nums.size(); i ++)
  55. {
  56. sum += nums[i];
  57.  
  58. res = min (res, max (sum , fun (nums, i + 1, m - 1, dp)));
  59. }
  60.  
  61. dp[idx][m] = res;
  62. return res ;
  63.  
  64. }
  65. int splitArray(vector<int>& nums, int m) {
  66.  
  67. vector <vector <int> > dp (1000 + 2, vector <int> (52, -1) );
  68.  
  69. return fun (nums, 0 , m-1 , dp);
  70.  
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement