Minimum Cost to Reduce Array

Given an array ARR of size N containing positive integers, the task is to reduce the size of the array to 1 by performing a specific operation multiple times. In one operation, you can merge any two adjacent elements of the array, and the cost of merging will be the sum of those two elements. Determine the minimum total cost of reducing the array to one element by using this operation.

Input:

int T - the number of test cases.
int N - the size of the array for each test case.
List of integers ARR - the array elements for each test case.

Output:

The minimum cost required to reduce the array to one element for each test case.

Example:

Input:
2
3
4 6 8
4
1 2 3 4
Output:
36
19
Explanation:

For the first test case, optimal way to merge would be (4, 6) → (10, 8), then (10, 8) → 18, that gives a total cost of 18 + 10 = 36.

For the second test case, optimal way to merge would be (1, 2), (3, 4), and then the result of these merges, giving a total cost of 19.

Constraints:

  • 1 <= T <= 50
  • 1 <= N <= 100
  • 1 <= ARR[i] <= 106
  • Time Limit: 1 sec

Note:

The operation will be performed N-1 times for an array of size N.

AnswerBot
3d

Find the minimum cost to reduce an array to one element by merging adjacent elements.

  • Iterate through the array and merge adjacent elements with the smallest sum each time.

  • Keep track of the total cost ...read more

Help your peers!
Add answer anonymously...
Tower Research Capital LLC SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter