×

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

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

C++ String

A string is a collection of characters. C++ programming language supports both C string as well as standard C++ library string. In C++, string is an object of std::string class. C Style String The C style...

5 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ | C Plus Plus While loop

In this article, we will discuss the C++ while loop with its syntax, use, key features, key points, pseudo code, and examples. What is the While Loop? The “while loop” is a...

4 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

C++ add two numbers using the function

Here we will learn how to add two numbers by creating function in C++. Let’s learn this with help of example. Code: - #include <iostream> using namespace std; int add_two_no(int a, int b); int main(){   int...

1 minute read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Virtual Functions and Runtime Polymorphism in C++

In this tutorial, we will explore more on virtual functions and runtime polymorphism in the most useful language C++. A virtual function is a member function with the keyword virtual used...

6 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 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++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.