fork download
  1. /*
  2. O(n ^ 3) solution
  3. The order in which we remove elements matters. That's why we will cover all possible ways to
  4. remove an element.In my solution dp[i][j] represents the answer when we removed elements
  5. from i to j. dp[i][j] will be maximum of (dp[i][k - 1] + a[i - 1]*a[k]*a[j + 1] + dp[k + 1][j])
  6. for k belonging to [i, j]. Basically we partition at different k, take the left and right
  7. subarray and the contribution of element at kth index.
  8. */
  9.  
  10. #include <bits/stdc++.h>
  11. using namespace std;
  12.  
  13. int main()
  14. {
  15. ios::sync_with_stdio(0);
  16. cin.tie(0);
  17.  
  18. int n;
  19. cin >> n;
  20. vector<int> a(n);
  21. for(int i = 0; i < n; i++) cin >> a[i];
  22.  
  23. vector<vector<int>> dp(n, vector<int>(n));
  24. for(int i = n - 1; i >= 0; i--) {
  25. for(int j = i; j < n; j++) {
  26.  
  27. // calculate dp[i][j]
  28. for(int k = i; k <= j; k++) {
  29. // we already remved [i, k - 1] and [k + 1, j]
  30. int cur = (k - 1 >= i ? dp[i][k - 1] : 0) + (k + 1 <= j ? dp[k + 1][j] : 0);
  31. int my = a[k] * (i > 0 ? a[i - 1] : 1) * (j + 1 < n ? a[j + 1] : 1);
  32. dp[i][j] = max(dp[i][j], cur + my);
  33. }
  34. }
  35. }
  36.  
  37. cout << dp[0][n - 1];
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 5552KB
stdin
5
3 5 1 8 2
stdout
217