The Wayback Machine - http://web.archive.org/web/20240901181942/https://www.geeksforgeeks.org/program-find-sum-elements-given-array/
Open In App

Program to find sum of elements in a given array

Last Updated : 29 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
74.98%
1.1L

Given an array of integers, find the sum of its elements.

Examples:

Input : arr[] = {1, 2, 3}
Output : 6
Explanation: 1 + 2 + 3 = 6

Input : arr[] = {15, 12, 13, 10}
Output : 50

Sum of elements of an array using Recursion:

The idea is to use recursive approach which calculates the sum of an array by breaking it down into two cases: the base case, where if the array is empty the sum is 0; and the recursive case, where the sum is calculated by adding the first element to the sum of the remaining elements which is computed through a recursive call with the array shifted by one position and size reduced by one.

Below is the implementation of the above approach:

C++
/* C++ Program to find sum of elements
in a given array using recursion */
#include <iostream>
using namespace std;

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    // base case
    if (n == 0) {
        return 0;
    }
    else {
        // recursively calling the function
        return arr[0] + sum(arr + 1, n - 1);
    }
}
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << sum(arr, n);
    return 0;
  
}
C
/* C++ Program to find sum of elements
in a given array using recursion */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    // base case
    if (n == 0) {
        return 0;
    }
    else {
        // recursively calling the function
        return arr[0] + sum(arr + 1, n - 1);
    }
}

int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("%d", sum(arr, n));

    return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {

    static int sum(int[] arr, int n)
    {

        // base or terminating condition
        if (n <= 0) {
            return 0;
        }

        // Calling method recursively
        return sum(arr, n - 1) + arr[n - 1];
    }

    public static void main(String[] args)
    {

        int arr[] = { 12, 3, 4, 15 };
        int s = sum(arr, arr.length);

        System.out.println(s);
    }
}
Python3
# python Program to find sum of elements
# in a given array using recursion

# function to return sum of elements
# in an array of size n


def sum1(arr):
    if len(arr) == 1:
        return arr[0]
    else:
        return arr[0] + sum1(arr[1:])


arr = [12, 3, 4, 15]
print(sum1(arr))

# This code is contributed by laxmigangarajula03
C#
using System;

public class GFG {

    static int sum(int[] arr, int n)
    {
        // base or terminating condition
        if (n <= 0) {
            return 0;
        }

        // Calling method recursively
        return sum(arr, n - 1) + arr[n - 1];
    }

    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int s = sum(arr, arr.Length);

        Console.Write(s);
    }
}

// This code is contributed by ksrikanth0498.
JavaScript
function sum(let arr, let n)
  {
    // base or terminating condition
    if (n <= 0) {
      return 0;
    }

    // Calling method recursively
    return sum(arr, n-1 ) + arr[n-1];
  }



    let arr = {12, 3, 4, 15};
    let s = sum(arr, arr.length);

    document.write(s);

Output
34

Time Complexity: O(n)
Auxiliary Space: O(n), Recursive stack space

Sum of elements of an array using Iteration:

The idea is to iterate through each element of the array and adding it to a variable called sum. The sum variable is initialized to 0 before the iteration starts. After the iteration, the final sum is returned.

Below is the implementation of the above approach:

C
/* C Program to find sum of elements
 in a given array */
#include <bits/stdc++.h>

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    int sum = 0; // initialize sum

    // Iterate through all elements
    // and add them to sum
    for (int i = 0; i < n; i++)
        sum += arr[i];

    return sum;
}

int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Sum of given array is %d", sum(arr, n));
    return 0;
}
C++
/* C++ Program to find sum of elements
in a given array */
#include <bits/stdc++.h>
using namespace std;

// function to return sum of elements
// in an array of size n
int sum(int arr[], int n)
{
    int sum = 0; // initialize sum

    // Iterate through all elements
    // and add them to sum
    for (int i = 0; i < n; i++)
        sum += arr[i];

    return sum;
}

// Driver code
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Sum of given array is " << sum(arr, n);
    return 0;
}

// This code is contributed by rathbhupendra
Java
/* Java Program to find sum of elements in a given array  */
class Test {
    static int arr[] = { 12, 3, 4, 15 };

    // method for sum of elements in an array
    static int sum()
    {
        int sum = 0; // initialize sum
        int i;

        // Iterate through all elements and add them to sum
        for (i = 0; i < arr.length; i++)
            sum += arr[i];

        return sum;
    }

    // Driver method
    public static void main(String[] args)
    {
        System.out.println("Sum of given array is "
                           + sum());
    }
}
Python3
# Python 3 code to find sum
# of elements in given array


def _sum(arr, n):

    # return sum using sum
    # inbuilt sum() function
    return(sum(arr))


# driver function
arr = []
# input values to list
arr = [12, 3, 4, 15]

# calculating length of array
n = len(arr)

ans = _sum(arr, n)

# display sum
print('Sum of the array is ', ans)

# This code is contributed by Himanshu Ranjan
C#
// C# Program to find sum of elements in a
// given array
using System;

class GFG {

    // method for sum of elements in an array
    static int sum(int[] arr, int n)
    {

        int sum = 0; // initialize sum

        // Iterate through all elements and
        // add them to sum
        for (int i = 0; i < n; i++)
            sum += arr[i];

        return sum;
    }

    // Driver method
    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int n = arr.Length;

        Console.Write("Sum of given array is "
                      + sum(arr, n));
    }
}

// This code is contributed by Sam007.
JavaScript
//JavaScript Program to find 
//sum of elements in a given array 

    // function to return sum of elements  
    // in an array of size n  
    function sum(arr) {  
        let sum = 0; // initialize sum  
  
        // Iterate through all elements  
        // and add them to sum  
        for (let i = 0; i < arr.length; i++)  
            sum += arr[i];  
  
        return sum;  
    }  
    
    // Driver code 
    let arr = [12, 3, 4, 15];
    console.log("Sum of given array is " + sum(arr));
    
 // This code is contributed by Surbhi Tyagi  
PHP
<?php
// PHP Program to find sum of 
// elements in a given array 

// function to return sum 
// of elements in an array
// of size n
function sum( $arr, $n)
{
    // initialize sum
    $sum = 0; 

    // Iterate through all elements 
    // and add them to sum
    for ($i = 0; $i < $n; $i++)
    $sum += $arr[$i];

    return $sum;
}

// Driver Code
$arr =array(12, 3, 4, 15);
$n = sizeof($arr);
echo "Sum of given array is ", 
                sum($arr, $n);

// This code is contributed by aj_36
?>

Output
Sum of given array is 34

Time Complexity: O(n)
Auxiliary Space: O(1)

Sum of elements of an array using Inbuild Methods:

The idea is to make use of built-in functions to find the sum of elements in a given array. These functions eliminate the need for explicit iteration, enhancing code simplicity.

Below is the implementation of above approach:

C++
/* C++ Program to find sum of elements
in a given array */
#include <bits/stdc++.h>
using namespace std;

// Driver code
int main()
{
    int arr[] = { 12, 3, 4, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // calling accumulate function, passing first, last
    // element and
    // initial sum, which is 0 in this case.
    cout << "Sum of given array is "
         << accumulate(arr, arr + n, 0);
    return 0;
}

// This code is contributed by pranoy_coder
Java
import java.util.Arrays;

public class GFG {
    // Driver code
    public static void main(String[] args) {
        int[] arr = {12, 3, 4, 15};
        int sum = Arrays.stream(arr).sum();
        System.out.println("Sum of given array is " + sum);
    }
}
Python3
# Python3 program to find sum of elements
# in a given array

# Driver code
if __name__ == "__main__":

    arr = [12, 3, 4, 15]
    n = len(arr)

    # Calling accumulate function, passing
    # first, last element and initial sum,
    # which is 0 in this case.
    print("Sum of given array is ", sum(arr))

# This code is contributed by ukasp
C#
// C# Program to find sum of elements in a
// given array
using System;
using System.Linq;

class GFG {

    // Driver method
    public static void Main()
    {

        int[] arr = { 12, 3, 4, 15 };
        int n = arr.Length;

        // calling LINQ Sum method on the array
        // to calculate the sum of elements in an array
        int sum = arr.Sum();

        Console.Write("Sum of given array is " + sum);
    }
}

// This code is contributed by abhishekmaran_.
JavaScript
// JavaScript program to find the sum of elements
// in a given array

// Driver code
const arr = [12, 3, 4, 15];
const n = arr.length;

// Calling the built-in reduce function to calculate the sum of elements in the array.
const sumOfArray = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log("Sum of given array is ", sumOfArray);

// This code is contributed by Yash Agarwal(yashagarwal2852002)

Output
Sum of given array is 34

Time Complexity: O(n)
Auxiliary Space: O(1)

Sum of elements of an array using Divide and Conquer:

The idea behind this approach is to utilize the divide and conquer strategy to find the sum of elements in a given array. This method involves three steps: Divide, Conquer and Combine.

1. Divide: Divide the array into smaller subarrays until each subarray has only one element.

2. Conquer: Calculate the sum of elements in each subarray. If the array contains only one element, return that element as the sum.

3. Combine: Combine the sums of subarrays to obtain the final sum of the entire array.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to find the sum of elements in an array using
// divide and conquer
int sum(vector<int>& arr, int low, int high)
{
    // Base case: If the array contains only one element
    if (low == high) {
        return arr[low];
    }
    else {
        int mid = (low + high) / 2;
        // Divide the array into two halves and recursively
        // calculate the sum
        int left_sum = sum(arr, low, mid);
        int right_sum = sum(arr, mid + 1, high);
        // Combine the sums of the subarrays
        return left_sum + right_sum;
    }
}

int main()
{
    vector<int> arr = { 12, 3, 4, 15 };
    int n = arr.size();
    cout << "Sum of given array is " << sum(arr, 0, n - 1);
    return 0;
}
// Nikunj Sonigara
Java
import java.util.ArrayList;
import java.util.List;

public class Main {
    // Function to find the sum of elements in an array
    // using divide and conquer
    public static int sum(List<Integer> arr, int low,
                          int high)
    {
        // Base case: If the array contains only one element
        if (low == high) {
            return arr.get(low);
        }
        else {
            int mid = (low + high) / 2;
            // Divide the array into two halves and
            // recursively calculate the sum
            int left_sum = sum(arr, low, mid);
            int right_sum = sum(arr, mid + 1, high);
            // Combine the sums of the subarrays
            return left_sum + right_sum;
        }
    }

    public static void main(String[] args)
    {
        List<Integer> arr = new ArrayList<>();
        arr.add(12);
        arr.add(3);
        arr.add(4);
        arr.add(15);
        int n = arr.size();
        System.out.println("Sum of given array is "
                           + sum(arr, 0, n - 1));
    }
}
Python3
# Function to find the sum of elements in an array using divide and conquer
def sum(arr, low, high):
    # Base case: If the array contains only one element
    if low == high:
        return arr[low]
    else:
        mid = (low + high) // 2
        # Divide the array into two halves and recursively calculate the sum
        left_sum = sum(arr, low, mid)
        right_sum = sum(arr, mid + 1, high)
        # Combine the sums of the subarrays
        return left_sum + right_sum

# Main function


def main():
    arr = [12, 3, 4, 15]
    n = len(arr)
    print("Sum of given array is", sum(arr, 0, n - 1))


# Calling the main function
main()
JavaScript
// Function to find the sum of elements in an array using divide and conquer
function sum(arr, low, high) {
    // Base case: If the array contains only one element
    if (low === high) {
        return arr[low];
    } else {
        let mid = Math.floor((low + high) / 2);
        // Divide the array into two halves and recursively calculate the sum
        let leftSum = sum(arr, low, mid);
        let rightSum = sum(arr, mid + 1, high);
        // Combine the sums of the subarrays
        return leftSum + rightSum;
    }
}

// Main function
function main() {
    let arr = [12, 3, 4, 15];
    let n = arr.length;
    console.log("Sum of given array is " + sum(arr, 0, n - 1));
}

// Calling the main function
main();

Output
Sum of given array is 34

Time Complexity: O(n log n)

Space Complexity: O(log n)



Similar Reads

Find the Array Permutation having sum of elements at odd indices greater than sum of elements at even indices
Given an array arr[] consisting of N integers, the task is to find the permutation of array elements such that the sum of odd indices elements is greater than or equal to the sum of even indices elements. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 4 2 3 Explanation:Consider the permutation of the given array as {1, 4, 2, 3}.Now, the sum of elem
6 min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Find elements in given Array that are a factor of sum of remaining elements
Given an array A[] of size N, the task is to find the elements in the array which are factors of the sum of the remaining element. So just select an element from an array and take the sum of the remaining elements and check whether the sum is perfectly divisible by the selected element or not. If it is divisible then return the element. Examples: I
11 min read
Program to find sum of elements in a given 2D array
Given a 2D array of order M * N, the task is to find out the sum of elements of the matrix. Examples: Input: array[2][2] = {{1, 2}, {3, 4}};Output: 10 Input: array[4][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};Output: 136 Approach: The sum of each element of the 2D array can be calculated by traversing through the matrix a
12 min read
Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions: In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.Every ith element in the array brr[] must satisfy brr[i] &gt;= arr[
5 min read
Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4, 6, 8, 2}, K = 2Output: 44Explanation:The followi
14 min read
Find array whose elements are XOR of adjacent elements in given array
Given an array arr[] consisting of N integers, the task is to re-construct an array arr[] such that the values in arr[] are obtained by doing XOR of the adjacent elements in the array. Print the array elements. Examples: Input: arr[ ] = {10, 11, 1, 2, 3} Output: 1 10 3 1 3 Explanation: At index 0, arr[0] xor arr[1] = 1At index 1, arr[1] xor arr[2]
5 min read
Sum of elements in given range from Array formed by infinitely concatenating given array
Given an array arr[](1-based indexing) consisting of N positive integers and two positive integers L and R, the task is to find the sum of array elements over the range [L, R] if the given array arr[] is concatenating to itself infinite times. Examples: Input: arr[] = {1, 2, 3}, L = 2, R = 8Output: 14Explanation:The array, arr[] after concatenation
10 min read
Find the index having sum of elements on its left equal to reverse of the sum of elements on its right
Given an array, arr[] size N, the task is to find the smallest index of the array such that the sum of all the array elements on the left side of the index is equal to the reverse of the digits of the sum of all the array elements on the right side of that index. If no such index is found then print -1. Examples: Input: arr[] = { 5, 7, 3, 6, 4, 9,
15+ min read
Find Sum of all unique sub-array sum for a given array.
Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. Note: Unique Sub-array sum means no other sub-array will have the same sum value. Examples: Input : arr[] = {3, 4, 5} Output : 40 Explanation: All possible unique sub-arra
10 min read
Find original Array from given Array where each element is sum of prefix and postfix sum
Given an array arr[] of length N, where arr is derived from an array nums[] which is lost. Array arr[] is derived as: arr[i] = (nums[0] + nums[1] + ... + nums[i]) + (nums[i] + nums[i+1] + ... + nums[N-1]). The task is to find nums[] array of length N. Examples: Input: N = 4, arr[] = {9, 10, 11, 10}Output: {1, 2, 3, 2}Explanation: If nums[] = {1, 2,
10 min read
Python3 Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Javascript Program to Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts
Given an array A[] of length N, where N is an even number, the task is to answer Q independent queries where each query consists of a positive integer K representing the number of circular shifts performed on the array and find the sum of elements by performing Bitwise OR operation on the divided array.Note: Each query begins with the original arra
5 min read
Find an element in array such that sum of left array is equal to sum of right array
Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4, 5] Input: 1 2 3Output: -1Explanation: No sub-arr
15+ min read
Construct an Array of size N in which sum of odd elements is equal to sum of even elements
Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: Input: N = 8 Output: 2 4 6 8 1 3 5 11 Explanation: The arr
7 min read
Find sum of all elements in a matrix except the elements in row and/or column of given cell?
Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row and j column. For every given cell index (i, j), find sums of all matrix elements except the elements present in i'th row and/or j'th column. Example: mat[][] = { {1, 1, 2} {3, 4, 6} {5, 3, 2} } Array of Cell Indexes: {(0, 0), (1, 1), (0, 1)} Output: 15, 10,
12 min read
Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array
Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices &amp; the count of odd elements at odd indices. Consider 1-based indexing Examples: Input: arr[] = {3, 4, 1, 5}Output: 0Explanation: Sum of even elements at even indices: 4 {4}Sum of odd elements at odd indices: 4
5 min read
Construct sum-array with sum of elements in given range
You are given an array of n-elements and an odd-integer m. You have to construct a new sum_array from given array such that sum_array[i] = ?arr[j] for (i-(m/2)) &lt; j (i+(m/2)). note : for 0 &gt; j or j &gt;= n take arr[j] = 0. Examples: Input : arr[] = {1, 2, 3, 4, 5}, m = 3 Output : sum_array = {3, 6, 9, 12, 9} Explanation : sum_array[0] = arr[0
7 min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of elements in arr2[] which are ? the elements of arr1[] arr
15 min read
Count array elements that can be represented as sum of at least two consecutive array elements
Given an array A[] consisting of N integers from a range [1, N], the task is to calculate the count of array elements (non-distinct) that can be represented as the sum of two or more consecutive array elements. Examples: Input: a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}Output: 5Explanation:The array elements satisfying the condition are: 4 = 3 + 1 5 = 1 + 4
11 min read
Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning
Given an array arr[] consisting of N integers and an integer M (initially 1), the task is to find the maximum sum of array elements chosen by Player A when two players A and B plays the game optimally according to the following rules: Player A starts the game.At every chance, X number of elements can be chosen from the beginning of the array, where
15+ min read
Minimum sum of values subtracted from array elements to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the sum of all the array elements required to be subtracted from each array element such that remaining array elements are all equal. Examples: Input: arr[] = {1, 2}Output: 1Explanation: Subtracting 1 from arr[1] modifies arr[] to {1, 1}. Therefore, the required sum is 1. I
4 min read
Make all array elements even by replacing any pair of array elements with their sum
Given an array arr[] consisting of N positive integers, the task is to make all array elements even by replacing any pair of array elements with their sum. Examples: Input: arr[] = {5, 6, 3, 7, 20}Output: 3Explanation: Operation 1: Replace arr[0] and arr[2] by their sum ( = 5 + 3 = 8) modifies arr[] to {8, 6, 8, 7, 20}.Operation 2: Replace arr[2] a
5 min read
Make all array elements even by replacing adjacent pair of array elements with their sum
Given an array arr[] of size N, the task is to make all array elements even by replacing a pair of adjacent elements with their sum. Examples: Input: arr[] = { 2, 4, 5, 11, 6 }Output: 1Explanation:Replacing a pair (arr[2], arr[3]) with their sum ( = 5 + 11 = 16) modifies arr[] to { 2, 4, 16, 16, 6 } Since all array elements are even, the required o
8 min read
Check if all array elements can be made divisible by K by replacing array elements with sum of pairs
Given an array arr[] of size N and a positive integer K, the task is to make every element of the array divisible by K by repeatedly selecting a pair of indices (i, j) and perform arr[i] = arr[i] + arr[j]. Examples: Input: arr[] = {3, 6, 3}, K = 6Output: TrueExplanation: Update arr[0] = arr[0] + arr[0].Update arr[2] = arr[2] + arr[2] Input: arr[] =
7 min read
Sum of Bitwise XOR of elements of an array with all elements of another array
Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[]. Examples: Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}Output: 7 34 11Explanation:For Q[0] ( = 3): Sum = 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.For Q[1] ( = 8): Sum = 5 ^ 8 + 2 ^ 8 + 3 ^ 8 = 34.For
9 min read
Queries to find the maximum and minimum array elements excluding elements from a given range
Given an array arr[] consisting of N integers and an array Q[][] consisting of queries of the form [L, R]., the task for each query is to find the maximum and minimum array elements in the array excluding the elements from the given range. Examples: Input: arr[] = {2, 3, 1, 8, 3, 5, 7, 4}, Q[][] = {{4, 6}, {0, 4}, {3, 7}, {2, 5}}Output: 8 17 43 17
15+ min read
Difference between ceil of array sum divided by K and sum of ceil of array elements divided by K
Given an array arr[] and an integer K, the task is to find the absolute difference between the ceil of the total sum of the array divided by K and the sum of the ceil of every array element divided by K. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 4Output: 2Explanation: Sum of the array = 21. Ceil of ( Sum of the array ) / K = 6.Sum of ceil of
6 min read