Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmReduce given array by replacing subarrays with values less than K with...

Reduce given array by replacing subarrays with values less than K with their sum

Given an array arr[] consisting of N positive integers and a positive integer K, the task is to update the given array by replacing the subarrays that are less than K with the sum of the elements in that subarray.

Examples:

Input: arr[] = {200, 6, 36, 612, 121, 66, 63, 39, 668, 108}, K = 100
Output: 200 42 612 121 168 668 108
Explanation:
The  subarray arr[1, 2] i.e., {6, 36} have elements less than K(= 100). So, adding and insert them into array as 6 + 36 = 42.
The  subarray arr[5, 7] i.e., {66, 63, 39} have elements less than K(= 100). So, adding and insert them into array as 66 + 63 + 39 = 168.
The modified array is {200, 42, 612, 121, 168, 668, 108}

Input: arr[] = {50, 25, 90, 21, 30}, K = 95
Output: 216

Approach: The given problem can be solved by traversing the array and keep the track of the sum having all elements less than K and update the array accordingly. Follow the steps below to solve the problem:

  • Initialize the variable, say sum as 0 that stores the sum of the subarray.
  • Initialize the vector, say res[] that stores the updated array arr[] satisfying the given criteria.
  • Traverse the given array and if the value of arr[i] < K, then update the value of sum as the sum + arr[i]. Otherwise, update the value of sum as 0 and add the value sum and arr[i] to the vector res[].
  • After completing the above steps, print the value stored in the vector res[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to replace all the subarray
// having values < K with their sum
void updateArray(vector<int>& arr, int K)
{
 
    // Stores the sum of subarray having
    // elements less than K
    int sum = 0;
 
    // Stores the updated array
    vector<int> res;
 
    // Traverse the array
    for (int i = 0; i < (int)arr.size(); i++) {
 
        // Update the sum
        if (arr[i] < K) {
            sum += arr[i];
        }
 
        // Otherwise, update the vector
        else {
            if (sum != 0) {
                res.push_back(sum);
            }
            sum = 0;
            res.push_back(arr[i]);
        }
    }
 
    if (sum != 0)
        res.push_back(sum);
 
    // Print the result
    for (auto& it : res)
        cout << it << ' ';
}
 
// Driver Code
int main()
{
 
    vector<int> arr = { 200, 6, 36, 612, 121,
                        66, 63, 39, 668, 108 };
    int K = 100;
    updateArray(arr, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to replace all the subarray
    // having values < K with their sum
    static void updateArray(int []arr, int K)
    {
 
        // Stores the sum of subarray having
        // elements less than K
        int sum = 0;
 
        // Stores the updated array
         ArrayList<Integer> res
            = new ArrayList<Integer>();
 
        // Traverse the array
        for (int i = 0; i < arr.length; i++) {
 
            // Update the sum
            if (arr[i] < K) {
                sum += arr[i];
            }
 
            // Otherwise, update the vector
            else {
                if (sum != 0) {
                    res.add(sum);
                }
                sum = 0;
                res.add(arr[i]);
            }
        }
 
        if (sum != 0)
            res.add(sum);
 
        // Print the result
        for (int i = 0; i < res.size(); i++)
            System.out.print(res.get(i) + " ");
    }
 
    // Driver Code
    public static void main(String []args)
    {
 
        int []arr = {200, 636, 612, 121,
                             6663, 39, 668, 108 };
        int K = 100;
        updateArray(arr, K);
    }
}
 
// This code is contributed by SURENDRA_GANGWAR.


Python3




# python program for the above approach
 
# Function to replace all the subarray
# having values < K with their sum
def updateArray(arr, K):
 
    # Stores the sum of subarray having
    # elements less than K
    sum = 0
 
    # Stores the updated array
    res = []
 
    # Traverse the array
    for i in range(0, int(len(arr))):
 
        # Update the sum
        if (arr[i] < K):
            sum += arr[i]
 
        # Otherwise, update the vector
        else:
            if (sum != 0):
                res.append(sum)
 
            sum = 0
            res.append(arr[i])
 
    if (sum != 0):
        res.append(sum)
 
    # Print the result
    for it in res:
        print(it, end=" ")
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [200, 6, 36, 612, 121, 66, 63, 39, 668, 108]
    K = 100
    updateArray(arr, K)
     
# This code is contributed by rakeshsahni


C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
class GFG {
 
    // Function to replace all the subarray
    // having values < K with their sum
    static void updateArray(List<int> arr, int K)
    {
 
        // Stores the sum of subarray having
        // elements less than K
        int sum = 0;
 
        // Stores the updated array
        List<int> res = new List<int>();
 
        // Traverse the array
        for (int i = 0; i < arr.Count; i++) {
 
            // Update the sum
            if (arr[i] < K) {
                sum += arr[i];
            }
 
            // Otherwise, update the vector
            else {
                if (sum != 0) {
                    res.Add(sum);
                }
                sum = 0;
                res.Add(arr[i]);
            }
        }
 
        if (sum != 0)
            res.Add(sum);
 
        // Print the result
        foreach(int it in res) Console.Write(it + " ");
    }
 
    // Driver Code
    public static void Main()
    {
 
        List<int> arr
            = new List<int>{ 200, 6,  36, 612, 121,
                             66,  63, 39, 668, 108 };
        int K = 100;
        updateArray(arr, K);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
 
        // Function to replace all the subarray
        // having values < K with their sum
        function updateArray(arr, K) {
 
            // Stores the sum of subarray having
            // elements less than K
            let sum = 0;
 
            // Stores the updated array
            let res = [];
 
            // Traverse the array
            for (let i = 0; i < arr.length; i++) {
 
                // Update the sum
                if (arr[i] < K) {
                    sum += arr[i];
                }
 
                // Otherwise, update the vector
                else {
                    if (sum != 0) {
                        res.push(sum);
                    }
                    sum = 0;
                    res.push(arr[i]);
                }
            }
 
            if (sum != 0)
                res.push(sum);
 
            // Print the result
            for (let it of res)
                document.write(it + ' ');
        }
 
        // Driver Code
 
 
        let arr = [200, 6, 36, 612, 121,
            66, 63, 39, 668, 108];
        let K = 100;
        updateArray(arr, K);
 
     // This code is contributed by Potta Lokesh
 
    </script>


Output: 

200 42 612 121 168 668 108

 

Time Complexity: O(N)
Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments