Answer to Question #228277 in C for gagandeep

Question #228277

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.


1
Expert's answer
2021-08-22T00:27:41-0400
#include <stdio.h>
// arr - array of ints
// n - size of array (arr), size of array must be >= 2
// k - multiplier for cost calculation
int min_cinsec_sum(int *arr, int n, int k) {
    int min = arr[0] + arr[1];
    for (int i = 1; i < n - 1; i++) {
        if (arr[i] + arr[i+1] < min)
            min = arr[i] + arr[i+1];
    }
    return min * k;
}
// driver for test function (doesn't use user input)
int main() {
    const int n = 7;
    int arr[] = {10, 4, 3, 8, 1, 4, 5};
    int k = 2;
    printf("%d\n", min_cinsec_sum(arr, n, k));
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS