Find the minimum index i for which the value sumprefix(i) + sumsuffix(i) is the minimum.

4. Given an array A of N positive integers, you are provided with two functions sumprefix(i) and sumsuffix(i).
The sumprefix(i) function computes the sum of first i numbers of the array.
The sumsuffix(i) function computes the sum of last N - i + 1 numbers of the array.
Your task is to find the minimum index i for which the value sumprefix(i) + sumsuffix(i) is the minimum. Which means you need to minimize the value of sumprefix(i) + sumsuffix(i)
and find the least index i for which this value is attained.

INPUT:
The first line of input contains the integer N denoting the number of elements in array A.
The second line contains the N separated elements of array A.

OUTPUT:
Output the single line containing the answer.



SOLUTION IN C

#include<stdio.h>
int sumprefix(int);
int sumsuffix(int);
int n,a[20];
int main()
{
int i,min,b[20];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
  b[i]=sumprefix(i)+sumsuffix(i);
min=b[1];
for(i=0;i<n;i++)
if(min>b[i])
      min=b[i];
for(i=0;i<n;i++)
{
  if(b[i]==min)
    break;
}
printf("%d",i);
}
int sumprefix(int i)
{
  if(i>=0)
    return (a[i]+sumprefix(i-1));
  else
    return 0;
}
int sumsuffix(int i)
{
  if(i<n)
    return (a[i]+sumsuffix(i+1));
  else
    return 0;

}

SOLUTION IN C++

#include<iostream>
using namespace std;
int sumprefix(int);
int sumsuffix(int);
int n,a[20];
int main()
{
int i,min,b[20];
cin>>n;
for(i=0;i<n;i++)
    cin>>a[i];
for(i=0;i<n;i++)
  b[i]=sumprefix(i)+sumsuffix(i);
min=b[1];
for(i=0;i<n;i++)
if(min>b[i])
      min=b[i];
for(i=0;i<n;i++)
{
  if(b[i]==min)
    break;
}
cout<<i;
}
int sumprefix(int i)
{
  if(i>=0)
    return (a[i]+sumprefix(i-1));
  else
    return 0;
}
int sumsuffix(int i)
{
  if(i<n)
    return (a[i]+sumsuffix(i+1));
  else
    return 0;
}

No comments:

Post a Comment

Total Pageviews