[InterviewBit] Merge elements

Merge elements

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <bits/stdc++.h>
int dp[202][202];
int psum[202];
int helper(vector<int>& A, int l, int r) {
if(l == r) return A[l];
if(dp[l][r] != -1) return dp[l][r];
int& res = dp[l][r] = INT_MAX;
for(int i = l; i < r; i++) res = min(res, helper(A,l,i) + helper(A,i+1,r));
res += psum[r + 1] - psum[l];
return res;
}

int Solution::solve(vector<int> &A) {
memset(dp,-1,sizeof dp);
for(int i = 0; i < A.size(); i++) psum[i + 1] = psum[i] + A[i];
return helper(A,0,A.size() - 1) - psum[A.size()];
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/08/PS/interviewbit/merge-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.