![]() |
VOOZH | about |
Given an array arr[] consisting of N integers and a positive integer M, the task is to find the sum of the first M elements of the array formed by the infinite concatenation of the given array arr[].
Examples:
Input: arr[] = {1, 2, 3}, M = 5
Output: 9
Explanation:
The array formed by the infinite concatenation of the given array arr[] is of the form {1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, ... }.
The sum of the first M(= 5) elements of the array is 1 + 2 + 3 + 1 + 2 = 9.Input: arr[] = {1}, M = 7
Output: 7
Approach: The given problem can be solved by using the Modulo Operator (%) and consider the given array as the circular array and find the sum of the first M elements accordingly. Follow the steps below to solve this problem:
Below is the implementation of the above approach:
9
Time Complexity: O(M)
Auxiliary Space: O(1)