# [C Language] guys.. What's wrong with my code? (First maximum number + second maximum number)

Problem : Format Input Input starts with an integer T, describing the number of test cases. Each test case starts with an integer N, the number of boxes that Lili has. The next line will contain N numbers Vi, each of them describe the value of the coin in the i-th box. It is guaranteed that the value will always be between -1000000 and 1000000. Format Output For each test case, output a single line consisting of ”Case #X: Y” where X is the test case number and Y is the maximum value Lili can get by choosing exactly 2 boxes. Constraints • 1 ≤ T ≤ 10 • 2 ≤ N ≤ 1, 000, 000 • −1, 000, 000 ≤ Vi ≤ 1, 000, 000 Sample Input (standard input) 3 5 1 2 3 4 5 4 4 4 4 4 3 10 1 2 Sample Output (standard output) Case #1: 9 Case #2: 8 Case #3: 12 *So, this problem want to sum the first and second maximum number *Idk why my code doesn't work at third sample case and some number, help me pleasee https://code.sololearn.com/cQy1ymCse096/?ref=app

10/19/2020 9:35:27 AM

Briana16 Answers

New AnswerBrianna it's giving me the expected output. That's a big negative number and there's no way a positive number can be smaller than that.

Hima like this? It's doesn't work for the second case #include<stdio.h> int main(){ int t; long int n, max1, max2, v[100]; scanf("%d", &t); for(int i=1; i<=t; i++){ if(t>=1 && t<=10){ scanf("%ld", &n);} if(n>=2 && n<=1000000){ for(long int j=0; j<n; j++){ scanf("%ld", &v[j]); } max1 = -1000000; for(long int j=0; j<n; j++){ if(max1<v[j]){ max1=v[j]; } } max2 = -1000000; for(long int j=0; j<n; j++){ if(v[j]!=max1 && v[j]>max2){ max2=v[j]; } } long int sum=max1+max2; printf("Case #%d: ", i); printf("%ld\n", sum); } } return 0; }

Brianna now see where it is wrong . int index; // declare index for(long int j=0; j<n; j++){ if(max1<v[j]){ max1=v[j]; index=j; //use index } } max2 = -1000; for(long int j=0; j<n; j++){ if((j!=index && v[j]>max2)){ //here as well max2=v[j]; } } Make this change and it works for everything.

Brianna Are you allowed to sort the array, or are you obliged to find the max1 and max2 without sorting the array? I think the easiest and fastest way is to sort the array in descending order; and then just pick the first two elements.

What do you mean you can't? Here's a reference for qsort function, there's an example too. I'm sure you can do this 👍 http://www.cplusplus.com/reference/cstdlib/qsort/

i dont knowwhere to put this part int index; // declare index for(long int j=0; j<n; j++){ if(max1<v[j]){ max1=v[j]; index=j; //use index } } max2 = -1000; for(long int j=0; j<n; j++){ if((j!=index && v[j]>max2)){ //here as well max2=v[j]; } }