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 , there are 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 n, int arr[]){int res;res = arr[0] + arr[1];for (int i = 1; i < n - 1; i++){res = min(res, arr[i] + arr[i + 1]);}return res;}int main(){int n = 3;int arr[n] = {3, 4, 2};cout << cheapestSubarray(n, arr) << "\n";return 0;}
No comments:
Post a Comment