Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum sum of Array formed by replacing each element with sum of adjacent elements
Next article icon

Find Array formed by adding each element of given array with largest element in new array to its left

Last Updated : 05 Nov, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.
Examples: 
 

Input: arr[] = {5, 1, 6, -3, 2} 
Output: {5, 6, 12, 9, 14} 
Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 
Element A1: Largest element to its left in the resultant array = 5. Hence the element at 1th index of the resultant array = 1 + 5 = 6 
Element A2: Largest element to its left in the resultant array = 6. Hence the element at 2nd index of the resultant array = 6 + 6 = 12 
Element A3: Largest element to its left in the resultant array = 12. Hence the element at 3rd index of the result array = -3 + 12 = 9 
Element A4: Largest element to its left in the resultant array = 12. Hence the element at 4th index of the result array = 2 + 12 = 14 
Therefore the resultant array = {5, 6, 12, 9, 14}
Input: arr[] = {40, 12, 62} 
Output: {40, 52, 114} 
 

 

Approach: 
In order to find such an array, each element of the new array will be computed one by one for each index in the range [0, N-1], according to the following rules: 
 

  1. For the starting index, i.e. 0, the new array will be empty. Hence there won’t be any largest element. In this case, the element at 0th index in the given array is copied down in the new array, i.e. 
     
B0 = A0  where A is the given array and        B is the new array

 

       2.For every other index in the range [1, N-1], first the largest element is found out to its left in the new array and then it is            added to the corresponding element of the original array, i.e., 
 

Bi = Ai + max(B0, B1, ..., Bi-1)  where A is the given array,        B is the new array, and       i is the current index

Below is the implementation of the above approach: 
 

C++




// C++ program to find Array formed by adding
// each element of given array with largest
// element in new array to its left
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find array B from array
// A such that Ai = Bi – max(B0…Bi-1)
void find_array(int a[], int n)
{
    // Initialising as 0 as first
    // element will remain same
    int x = 0;
     
    for (int i = 0; i < n; i++) {
 
        // restoring values of B
        a[i] += x;
 
        cout << a[i] << ' ';
         
        // Find max value
        x = max(x, a[i]);
    }
}
 
// Driver code
int main()
{
    int a[] = {40, 12, 62};
    int n = sizeof(a) / sizeof(a[0]);
     
    // Function call
    find_array(a, n);
     
    return 0;
}
 
 

Java




// Java program to find Array formed by adding
// each element of given array with largest
// element in new array to its left
 
public class GFG
{
     
// Function to find array B from array
// A such that Ai = Bi – max(B0…Bi-1)
static void find_array(int []a, int n)
{
    // Initialising as 0 as first
    // element will remain same
    int x = 0;
     
    for (int i = 0; i < n; i++) {
 
        // restoring values of B
        a[i] += x;
 
        System.out.print(a[i] + " ");
         
        // Find max value
        x = Math.max(x, a[i]);
    }
}
 
// Driver code
public static void main(String []args)
{
    int []a = {40, 12, 62};
    int n = a.length ;
     
    // Function call
    find_array(a, n);
}
}
 
// This code is contributed by Yash_R
 
 

Python3




# Python3 program to find Array formed by adding
# each element of given array with largest
# element in new array to its left
 
# Function to find array B from array
# A such that Ai = Bi – max(B0…Bi-1)
def find_array(a,  n) :
 
    # Initialising as 0 as first
    # element will remain same
    x = 0;
     
    for i in range(n) :
 
        # restoring values of B
        a[i] += x;
 
        print(a[i],end= ' ');
         
        # Find max value
        x = max(x, a[i]);
 
# Driver code
if __name__ == "__main__" :
 
    a = [40, 12, 62];
    n = len(a);
     
    # Function call
    find_array(a, n);
     
# This code is contributed by Yash_R
 
 

C#




// C# program to find Array formed by adding
// each element of given array with largest
// element in new array to its left
using System;
 
class gfg
{
     
// Function to find array B from array
// A such that Ai = Bi – max(B0…Bi-1)
static void find_array(int []a, int n)
{
    // Initialising as 0 as first
    // element will remain same
    int x = 0;
     
    for (int i = 0; i < n; i++) {
 
        // restoring values of B
        a[i] += x;
 
        Console.Write(a[i] + " ");
         
        // Find max value
        x = Math.Max(x, a[i]);
    }
}
 
// Driver code
public static void Main(string []args)
{
    int []a = {40, 12, 62};
    int n = a.Length ;
     
    // Function call
    find_array(a, n);
}
}
 
// This code is contributed by Yash_R
 
 

Javascript




<script>
 
// Javascript program to find Array formed by adding
// each element of given array with largest
// element in new array to its left
 
// Function to find array B from array
// A such that Ai = Bi – max(B0…Bi-1)
function find_array(a, n)
{
    // Initialising as 0 as first
    // element will remain same
    let x = 0;
     
    for (let i = 0; i < n; i++) {
 
        // restoring values of B
        a[i] += x;
 
        document.write(a[i] + ' ');
         
        // Find max value
        x = Math.max(x, a[i]);
    }
}
 
// Driver code
 
    let a = [40, 12, 62];
    let n = a.length;
     
    // Function call
    find_array(a, n);
     
  
// This code is contributed by Mayank Tyagi
 
</script>
 
 
Output: 
40 52 114

 

Time Complexity:  O(N)

Auxiliary Space: O(1)



Next Article
Maximum sum of Array formed by replacing each element with sum of adjacent elements

I

IshwarGupta
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Maximize every array element by repeatedly adding all valid i+a[i]th array element
    Given an array of integers, arr[] of size N, the task is to print all possible sum at each valid index, that can be obtained by adding i + a[i]th (1-based indexing) subsequent elements till i ? N. Examples: Input: arr[] = {4, 1, 4}Output: 4 5 4Explanation:For i = 1, arr[1] = 4.For i = 2, arr[2] = ar
    5 min read
  • Queries to find the maximum array element after removing elements from a given range
    Given an array arr[] and an array Q[][] consisting of queries of the form of {L, R}, the task for each query is to find the maximum array element after removing array elements from the range of indices [L, R]. If the array becomes empty after removing the elements from given range of indices, then p
    10 min read
  • Maximum sum of Array formed by replacing each element with sum of adjacent elements
    Given an array arr[] of size N, the task is to find the maximum sum of the Array formed by replacing each element of the original array with the sum of adjacent elements.Examples: Input: arr = [4, 2, 1, 3] Output: 23 Explanation: Replacing each element of the original array with the sum of adjacent
    9 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
    15+ min read
  • Maximize product of array by replacing array elements with its sum or product with element from another array
    Given two arrays A[] and B[] consisting of N integers, the task is to update array A[] by assigning every array element A[i] to a single element B[j] and update A[i] to A[i] + B[j] or A[i] * B[j], such that the product of the array A[] is maximized. Note: Every array element in both the arrays can b
    7 min read
  • Largest element smaller than current element on left for every element in Array
    Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index. Note: If no such element is found then print -1. Examples: Input: arr[] = {2, 5, 10} Output: -1 2 5 Explanation : I
    11 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
    10 min read
  • Maximize Array sum by adding multiple of another Array element in given ranges
    Given two arrays X[] and Y[] of length N along with Q queries each of type [L, R] that denotes the subarray of X[] from L to R. The task is to find the maximum sum that can be obtained by applying the following operation for each query: Choose an element from Y[]. Add multiples with alternate +ve an
    15+ min read
  • Generate an array consisting of most frequent greater elements present on the right side of each array element
    Given an array A[] of size N, the task is to generate an array B[] based on the following conditions: For every array element A[i], find the most frequent element greater than A[i] present on the right of A[i]. Insert that element into B[].If more than one such element is present on the right, choos
    9 min read
  • Largest number in given Array formed by repeatedly combining two same elements
    Given an array arr[], the task is to find the largest number in given Array, formed by repeatedly combining two same elements. If there are no same elements in the array initially, then print the output as -1.Examples: Input: arr = {1, 1, 2, 4, 7, 8} Output: 16 Explanation: Repetition 1: Combine 1s
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences