We are given a sequence of a numbers n . The decrease in the sequence a defined as the replacement of the elements a[i] and a[i+1] by max(a[i],a[i+1]) .
Each reduction operation has a cost defined as max(a[i],a[i+1]) . After n-1 contractions, a sequence of length 1 obtained.
Now our goal is to print the cost of optimal reduction of a given sequence a so that the resulting sequence of length 1 has a minimum cost.
eg:.
1 2 3 Output : 5
The solution O (N ^ 2) is trivial. Any ideas?
EDIT1: People ask about my idea, so my idea was to go through the sequence in pairs and check the cost for each pair and finally reduce the pair at the lowest cost.
1 2 3 2 3 <=== Cost is 2
So reduce the sequence above to
2 3
now cross the sequence again, we get the value as 3
2 3 3 <=== Cost is 3
Thus, the total cost is 2 + 3 = 5
The above algorithm has O (N ^ 2). That is why I asked for a more optimized idea.
source share