Find minimum sum such that one of every three consecutive elements is taken in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of n elements. The task is to find the minimum sum of elements from the array. Such that at least one element one element is picked out of every three consecutive elements in that array. So if the array is like [1, 2, 3, 6, 7, 1]. The output is 4. So if we pick 3 and 1, then (3 + 1 = 4). So there are some subarrays of consecutive elements like [1, 2, 3], [2, 3, 6], [3, 6, 7], [6, 7, 1], we have picked one element from every subarray.

Consider sum(i) will return minimum possible sum, where arr[i] is part of the solution and is last picked element. Then our result is min of sum(i – 1), sum(i – 2), sum(i – 3). As we can see that this has overlapping subproblem, then we can use the dynamic programming approach to solve this.

Example

 Live Demo

#include <iostream>
using namespace std;
int minOfThree(int a, int b, int c) {
   return min(min(a, b), c);
}
int getMinSum(int arr[], int n) {
   int sum[n];
   sum[0] = arr[0];
   sum[1] = arr[1];
   sum[2] = arr[2];
   for (int i=3; i<n; i++)
   sum[i] = arr[i] + minOfThree(sum[i-3], sum[i-2], sum[i-1]);
   return minOfThree(sum[n-1], sum[n-2], sum[n-3]);
}
int main() {
   int arr[] = {1, 2, 3, 20, 2, 10, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Minimum sum is: " << getMinSum(arr, n);
}

Output

Minimum sum is: 4
raja
Published on 18-Dec-2019 10:33:45
Advertisements