Problem solved using sorting
PROBLEM STATEMENT:
There is a girl named "winnie the pooh" .she have a bag of chocolate packets each with a different number of chocolates ,her father asked her to take only two packets from whole bag. winnie the pooh is very fond of chocolates, she asked you to help her so that she gets maximum number of chocolates from selected packets. Help winnie the pooh to select two packets from bag so that they have maximum sum of chocolates.
Explanation:
Here in this problem there is a array which says number of chocolates in each packet in a random order,we need to find two numbers such that their sum is maximum.
INPUT GIVEN:
N : number of elements in array
Array of length l
SOLUTION:
APPROACH 1:
Here we can find maximum sum of two elements by adding ever two elements and finding maximum from calculated values
int a[6]={4,5,2,3,17};
int sum[12],k=0,max=0;
for(int i=0;i<6;i++)
{
for(int j=i+1;j<6;j++)
{
sum[k++]=a[i]+a[j];
}
}
for(int i=0;i
{
if(sum[i]>max)
{
max=sum[i];
}
}
printf("max sum is %d",max);
The above approach uses O(n*n) time and O(k) space
TIME COMPLEXITY:this means how much time does the program takes to complete it's execution based on input given.
SPACE COMPLEXITY:this means amount of auxiliary(extra) space used by program to execute based on input given.
APPROACH 2:
In this method we sort the array and then just add last two array elements
this method reduces space complexity and even time complexity only if we use sorting technique other than bubble sort.But initially we can use bubble sort.By using bubble sort we don't reduce time complexity.
but by using other techniques we can reduce complexity up to O(nlogn)
int a[6]={4,5,2,3,17};
for (i = 0; i < n-1; i++)
{
for (j = 0; j < n-i-1; j++)
{
if (a[j] > a[j+1])
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf("%d is maximum sum",a[n-1]+a[n-2]);//a[n-1]+a[n-2] gives sum of last two elements of array
HOPE THIS HELPS..
THANK YOU......
HAPPY CODING.............