简体   繁体   中英

How to subtract smallest element from sum of array elements

For each test case t, I need to input n, the number of elements in an array, and input those elements. Then I have to subtract the smallest element in the array from the sum of all the other elements. Here is my code, but I keep getting TLE:

#include <bits/stdc++.h>

int main(void) {
    int t;
    std::cin >> t;
    while (t --) {
        int n, sum = 0, a, k = 100000;
        std::cin >> n;
        while (n --) {
            std::cin >> a;
            if (a < k) {
                k = a;
            } else {
                sum += a;
            }
            n --;
        }
        std::cout << abs(sum - k) << "\n";
    }
}

Sample Input:

3
5
20 16 8 2 13
6
16 9 12 20 15 14
4
2 2 2 2

Sample Output:

55
68
4

In this if statement

if (a < k) {

you are comparing each entered value with the current value of k and if it is less than k you are not adding it to sum .

For example for this sequence of numbers

20 16 8 2 13

20 is less than the initial value of k. So now k is equal to 20 and the number is not added to sum.. The next number 16 is also less than the current value of k. And again it is not added to sum.

You need to sum all numbers and at the same time find the minimum number. And then after the loop subtract the minimal number from sum.

Also this statement

 n --;

is redundant.

The program can look the following way

#include <iostream>

int main() 
{
    unsigned int t = 0;
    
    std::cin >> t;
    
    while ( t-- )
    {
        unsigned int n = 0;
        long long int sum = 0;
        int min = 0;
        bool first = true;
        
        std::cin >> n;
        
        while ( n-- )
        {
            int x;
            
            std::cin >> x;
            
            if ( first || x < min )
            {
                first = false;
                min = x;
            }
            sum += x;
        }
        
        std::cout << ( sum < min ? min - sum : sum - min ) << '\n';
    }
    
    return 0;
}

For the input

1
5
20 16 8 2 13

the program output is

57

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM