×

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1 and k2, calculate the sum of all entries in the array between the smallest k1 and k2 elements. It's safe to assume that (1 = k1 k2 = n) and all array items are unique.

Method No. 1 (Sorting)

We will sort the given array using an O(n log n) sorting algorithm, such as Merge Sort or Heap Sort, and then return the sum of all entries in the sorted array between indexes k1 and k2.

The following is how the aforementioned concept was put into action:

C++ Program:

// CPP to determine the sum of all elements in a given array between the K1'th and K2'th smallest elements.
#include <bits/stdc++.h> 
using namespace std; 
int sum_between_two_Kth ( int array [], int num, int k1, int k2 ) 
{ 
    // Sorting the given array
    sort ( array, array + num ); 


    return accumulate ( array + k1, array + k2 - 1, 0 ); 
} 
// Driver Code
int main () 
{ 
    int array [] = { 21, 9, 23, 5, 13, 11, 15 }; 
    int k1 = 3, k2 = 6; 
    int num = sizeof ( array ) / sizeof ( array [0] ); 
    cout << sum_between_two_Kth ( array, num, k1, k2 ); 
    return 0; 
}

Output:

28

Time Complexity: O(n log n)

Method No. 2 (Using Min Heap)

Using a min heap, we can improve the above approach.

1) Create a heap from all array elements. (This operation takes O(n) time.)

2) Perform at least k1 extractions. (It takes O(K1 Log n) seconds to complete this phase.)

3) Extract k2 - k1 - 1 times and combine all extracted parts. (This phase takes O ((K2 - k1) * Log n) time to complete.)

C++Program:

#include <bits/stdc++.h> 
using namespace std; 
  
int num = 7; 
void minheapify ( int array [], int index ) 
{ 
    int s = index; 
    int l = 2 * index + 1; 
    int r = 2 * index + 2; 
  
    if ( l < num && array [ l ] < array [ s ] ) 
        s = l; 
  
    if ( r < num && array [ r ] < array [ s ] ) 
        s = r; 
  
    if ( s != index ) { 
        swap ( array [s], array [index] ); 
        minheapify ( array, s ) ; 
    } 
} 
int main () 
{ 
    int i = 0; 
    int k1 = 3; 
    int k2 = 6; 
    int array [] = { 21, 9, 23, 5, 13, 11, 15 }; 
    int answer = 0; 
    for ( i = ( num / 2) - 1; i >= 0; i-- ) { 
        minheapify ( array, i ); 
    } 
    k1--; 
    k2--; 
    for ( i = 0; i <= k1; i++ ) { 
        array [0] = array [ num - 1]; 
        num--; 
        minheapify ( array, 0 ); 
    }
    for ( i = k1 + 1; i < k2; i++ ) { 
        answer += array [0]; 
        array [0] = array [ num - 1 ]; 
        num--; 
        minheapify ( array, 0) ; 
    } 
    cout << answer; 
    return 0; 
}

Output:

28

This method's overall time complexity is O(n + k2 Log n), which is faster than the sorting-based method.


Related Topics

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Object in C++

In this article, we will learn about Object in C++. In short, an object is a stateful entity with behaviour. Data is referred to as state, and functionality is referred to...

3 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.