Find minimum cost to buy all books in C++


Suppose we have an array of n elements. These are the ratings of them. Find the minimum cost to buy all books, with the following condition −

  • Cost of each book would be at-least 1 dollar
  • A book has higher cost than an adjacent (left or right) if rating is more than the adjacent.

So for example, if the rating array is like [1, 3, 4, 3, 7, 1], Then the output is 10, As 1 + 2 + 3 + 1 + 2 + 1 = 10

To solve this, we have to make two arrays called LtoR, and RtoL, and fill them with 1, now follow these steps −

  • Traverse left to right, then fill LtoR, and update it by seeing previous rating of the given array. We are not caring about the next rating of given array
  • Traverse right to left, then fill RtoL, and update it by seeing previous rating of the given array. We are not caring about the next rating of given array
  • For maximum value of ith position in both array LtoR and RtoL, then add it to the result.

Example

 Live Demo

#include<iostream>
using namespace std;
int getMinCost(int ratings[], int n) {
   int res = 0;
   int LtoR[n];
   int RtoL[n];
   for(int i = 0; i<n; i++){
      LtoR[i] = RtoL[i] = 1;
   }
   for (int i = 1; i < n; i++)
   if (ratings[i] > ratings[i - 1])
      LtoR[i] = LtoR[i - 1] + 1;
   for (int i = n - 2; i >= 0; i--)
      if (ratings[i] > ratings[i + 1])
         RtoL[i] = RtoL[i + 1] + 1;
   for (int i = 0; i < n; i++)
      res += max(LtoR[i], RtoL[i]);
   return res;
}
int main() {
   int ratings[] = { 1, 6, 8, 3, 4, 1, 5, 7 };
   int n = sizeof(ratings) / sizeof(ratings[0]);
   cout << "Minimum cost is: " << getMinCost(ratings, n);
}

Output

Minimum cost is: 15

Updated on: 18-Dec-2019

165 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements