Idleness_Limit_Exceeded's blog

By Idleness_Limit_Exceeded, history, 6 years ago, In English

Bob has an array of size n. He loves to play with these n numbers. Each time he plays with them, he picks up any two consecutive numbers and adds them. On adding both the numbers, it costs him k*(sum of both number). Find the minimum cost of adding all the numbers in the array.

Example 1- n=3 & k=2; Array elements are {1,2,3} Output : 18

Example 2- n=4 & k=3; Array elements are {4,5,6,7} Output : 132

| Write comment?
»
6 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

why you all are downvoting the post! Its really a nice problem. Not just brute force like sort it or something like that. If you get the solution, Kindly let me know in the comments. It's definitely NOT SO EASY ONE!!!

»
6 years ago, hide # |
 
Vote: I like it +19 Vote: I do not like it

Isn't it just greedy? Put all in a priority queue, take 2 minimal, add them, put the sum back in the queue?

Also, it reminds me of how you encode symbols with Huffman codes — each symbol has its weight (= frequency) and you build a binary tree such as sum(char.freq * len(char.code)) is minimal. This problem can also be thought as a binary tree where you put numbers in leaves and want to minimize sum(x * depth[x])