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 = arr;
sum = arr;
sum = arr;
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);
cout << "Minimum sum is: " << getMinSum(arr, n);
}

Output

Minimum sum is: 4