Cheapest Subarray

Given an array of integers and you need to tell the cost of the cheapest possible subarray of length at least two.

A subarray is the sequence of consecutive elements of the array and the cost of a subarray is the sum of the minimum and the maximum value in the subarray. 

Note: In an array of length n, there are n(n1)2 subarrays whose length is at least 2.

Example:

Input:  n = 3, arr =[3,4,2]
Output: 6

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int cheapestSubarray(int nint arr[])
{

    int res;
    res = arr[0] + arr[1];

    for (int i = 1i < n - 1i++)
    {
        res = min(resarr[i] + arr[i + 1]);
    }
    return res;
}
int main()
{

    int n = 3;

    int arr[n] = {342};

    cout << cheapestSubarray(narr<< "\n";

    return 0;
}


No comments:

Post a Comment