SUM OF POSITIVE NUMBERS
Problem Description
Write a program to find the sum of positive numbers in an array.
Input Format:
Input consists of n+1 integers. The first integer corresponds to n , the size of the array. The next ?n? integers correspond to the elements in the array. Assume that the maximum value of n is 15.
Output Format:
Refer sample output for details
CODING ARENA
#include <stdio.h>
int main()
{
int num,a[100],sum=0,i;
scanf("%d",&num);
for(i=0;i<num;i++)
scanf("%d",&a[i]);
for(i=0;i<num;i++)
{
if(a[i]>=0)
{
sum=sum+a[i];
}
}
printf("sum=%d",sum);
return 0;
}
Test Case 1
Input (stdin)5
2 3 6 8 -1
Expected Output
sum=19
Test Case 2
Input (stdin)5
-1 -2 -3 -4 -5
Expected Output
sum=0
i think we can do using DAC-algo and this will reduce time complexity to O(Log2N) whereas the way you are doing will take O(N) time.
ReplyDeleteAlgorithm:
int SumOfPos(p,q){
if(p==q)
if(a[p]<=0)
return 0;
else
return a[p];
else{
mid = (p+q)/2;
num1 = SumOfPos(p,mid);
num2 = SumOfPos(mid+1,q);
return (num1+num2);
}
}