INPUT { 5 ,4, 3, 2, 1 }
OUTPUT {24,30,40,60,120}as a[0]=(4*3*2*1)=24
a[1]=(5*3*2*1)
In this we can maintain two arrays lh[] and rh[]
where lh[i]= a[0] * a[1]*........*a[i-1]
and rh[i]= a[i+1] * a[i+2]*........*a[n] where n is the last index of array
Here is my code
#include<stdio.h>
int main()
{
int arr[5]={5,4,3,2,1};
int lh[5];// will contain the product of all elements to the left
int rh[5];// will contain the product of all elements to the right
int prod=1;
for(int k=0;k<5;k++)
{
lh[k]=prod;
prod=prod*arr[k]; }
prod=1;
for(int k=4;k>=0;k--)
{
rh[k]=prod;
prod=prod*arr[k]; }
for(int k=0;k<5;k++)
arr[k]=lh[k]*rh[k];
for(int k=0;k<5;k++)
printf("%d\t",arr[k]);
return 0;
}
Please tell me if any optimizations are required..................
No comments:
Post a Comment