Sum without maximum#7831

Sum without maximum (Editorial)

First, find the maximum element of the array. Then compute the sum of all elements whose values differ from the maximum. Note that the maximum value may occur in the array more than once; in that case, all such elements are excluded from the sum.

Example

The largest element in the given example is .

The sum of elements not equal to the maximum is 5 + 3 + 4 + 6 = 18.

Algorithm implementation

Declare the array.

int m[101];

Read the input data.

scanf("%d",&n);
for(i = 0; i < n; i++)
  scanf("%d",&m[i]);

Compute the maximum element .

mx = -100;
for(i = 0; i < n; i++)
  if (m[i] > mx) mx = m[i];

Find the sum of all elements in the array that are not equal to the maximum .

s = 0;
for(i = 0; i < n; i++)

If the current element is not equal to the maximum , add it to the sum .

  if (m[i] != mx) s += m[i];

Print the sum.

printf("%d\n",s);

Algorithm implementation — STL

Read the input data.

scanf("%d", &n);
v.resize(n);
for (i = 0; i < n; i++)
  scanf("%d", &v[i]);

Compute the maximum element .

mx = *max_element(v.begin(), v.end());

Replace all occurrences of in the array with .

replace(v.begin(), v.end(), mx, 0);

Compute the sum of all elements in the modified array (with the maximum elements replaced by ).

s = accumulate(v.begin(), v.end(), 0);

Print the answer — the sum of all elements excluding the maximum ones.

printf("%d\n", s);

Java implementation

import java.util.*;

public class Main 
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);
    int n = con.nextInt();
    int m[] = new int[n];
    for (int i = 0; i < n; i++)
      m[i] = con.nextInt();
    
    int max = -100;
    for(int i = 0; i < n; i++)
      if (m[i] > max) max = m[i];

    int s = 0;
    for(int i = 0; i < n; i++)
      if (m[i] != max) s += m[i];
    
    System.out.println(s);
    con.close();
  }
}

Python implementation

Read the input data.

n = int(input())
lst = list(map(int,input().split()))

Find the maximum element in the list .

mx = max(lst)

In the variable compute the sum of all elements in the list that are not equal to the maximum value .

sum = 0
for x in lst:
  if x != mx: sum += x

Print the answer.

print(sum)

Python implementation — summation

Read the input data.

n = int(input())
lst = list(map(int,input().split()))

Find the maximum element in the list .

mx = max(lst)

In the variable compute the sum of all elements in the list that are not equal to the maximum value .

res = sum(x for x in lst if x != mx)

Print the answer.

print(res)