Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Easy
  • Last Updated : 23 Sep, 2021

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);
 
            // Prlet 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(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :