Header Ad

HackerEarth Cheapest Subarray problem solution

In this HackerEarth Cheapest Subarray problem solution Visuals can be deceptive, and so can be the titles of the contest, but not every time you'll be asked tough questions in an EASY contest.

In this problem, you will be 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.


HackerEarth Cheapest Subarray problem solution


HackerEarth Cheapest Subarray problem solution.

#include "bits/stdc++.h"

using namespace std;

int main() {
int t, n;
cin >> t;
while(t--) {
cin >> n;
vector <int> v(n);
for(int i = 0; i < n; i++) {
cin >> v[i];
}
int ans = v[0] + v[1];
for(int i = 1; i + 1 < n; i++) {
ans = min(ans, v[i] + v[i + 1]);
}
cout << ans << endl;
}
return 0;
}


Second solution

#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
assert(cin>>t);
assert(t>=1 && t<=10);
while(t--)
{
int n,a[20005];
assert(cin>>n);
assert(n>=2 && n<=2e4);
for(int i=0;i<n;i++)
assert(cin>>a[i]),assert(a[i]>=1 && a[i]<=2e4);
int ans=1000000000;
for(int i=1;i<n;i++)
{
ans=min(ans,a[i]+a[i-1]);
}
cout<<ans<<"\n";
}
return 0;
}

Post a Comment

0 Comments