[InterviewBit] Potions

Potions

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

pair<int, int> helper(int i, int j, vector<int> &A, vector<vector<pair<int,int>>> &dp){
pair<int, int>& res = dp[i][j];
if(dp[i][j].first != -1) return res;
if(i == j) return res = {0,A[i]};
if(j == i + 1) res = {A[i] * A[j], (A[i] + A[j]) % 100};

res = {INT_MAX, INT_MAX};
for(int k = i + 1; k <= j; k++) {
auto l = helper(i,k-1,A,dp);
auto r = helper(k,j,A,dp);

pair<int,int> now = {l.first + r.first + l.second * r.second, (l.second + r.second) % 100};
if(now.first < res.first) res = now;
}
return res;
}

int Solution::minSmoke(vector<int> &A) {
if(A.size() == 1) return 0;
if(A.size() == 2) return A[0] * A[1];
vector<vector<pair<int,int>>> dp(A.size(), vector<pair<int,int>>(A.size(), {-1, -1}));
return helper(0,A.size() - 1, A, dp).first;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/16/PS/interviewbit/potions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.