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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Maximum sum subsequence of length K | Set 2
Next article icon

Maximum subsequence sum possible by multiplying each element by its index

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the maximum subsequence sum by multiplying each element of the resultant subsequence by its index(1-based indexing).

Examples:

Input: arr[] = {-1, 2, -10, 4, -20} 
Output: 15 
Explanation: 
For the subsequence {-1, 2, 4}, sum of the given subsequence after performing the given operations = 1*(-1) + 2*2 + 3*4 = 15, which is maximum possible.

Input: arr[] = {1, 0, -1, 2} 
Output: 7 
Explanation: 
For the subsequence {1, 0, 2}, sum of the given subsequence after performing the given operations = 1*1 + 2*0 + 3*2 = 7, which is maximum possible.

Naive Approach: The idea is to generate all possible subsequences from the array using recursion and calculate the required sum for each subsequence and print the maximum sum. 

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

Efficient Approach: The above approach can be optimized using Dynamic Programming as the problem contains many overlapping subproblems. Below are the steps:

  • Initialize an auxiliary matrix dp[][], where dp[i][j] stores the maximum value of the subsequence of length j up to index i.
  • Traverse the given array and for each element, there are 2 possibilities: 
    • Either to include the current element into the subsequence sum and increment the number of elements in subsequence.
    • Or exclude the current element from the subsequence and proceed to the next element.
  • Therefore, the recurrence relation is given by the following equation:

 dp[i][j] = max(a[i] * j + maximumSum(j + 1, i + 1), maximumSum(j, i + 1)) 

  • Keep updating the dp[][] table by using the above recurrence relation for every index and return the maximum sum possible from the entire array.
  • Print the maximum value after the above steps.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Initialize dp array
int dp[1005][1005];
 
// Function to find the maximum
// sum of the subsequence formed
int maximumSumUtil(int a[], int index,
                   int count, int n)
{
    // Base Case
    if (index > n || count > n + 1) {
        return 0;
    }
 
    // If already calculated
    // state occurs
    if (dp[index][count] != -1)
        return dp[index][count];
 
    // Include the current element
    int ans1 = maximumSumUtil(a, index + 1,
                              count + 1, n)
               + a[index] * count;
 
    // Exclude the current element
    int ans2 = maximumSumUtil(a, index + 1,
                              count, n);
 
    // Update the maximum ans
    return (dp[index][count]
            = max(ans1, ans2));
}
 
// Function to calculate maximum sum
// of the subsequence obtained
int maximumSum(int arr[], int N)
{
    // Initialise the dp array with -1
    memset(dp, -1, sizeof(dp));
 
    // Print the maximum sum possible
    cout << maximumSumUtil(arr, 0, 1,
                           N - 1);
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { -1, 2, -10, 4, -20 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maximumSum(arr, N);
 
    return 0;
}
 
 

Java




// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Initialize dp array
static int [][]dp = new int[1005][1005];
 
// Function to find the maximum
// sum of the subsequence formed
static int maximumSumUtil(int a[], int index,
                          int count, int n)
{
  // Base Case
  if (index > n || count > n + 1)
  {
    return 0;
  }
 
  // If already calculated
  // state occurs
  if (dp[index][count] != -1)
    return dp[index][count];
 
  // Include the current element
  int ans1 = maximumSumUtil(a, index + 1,
                            count + 1, n) +
                            a[index] * count;
 
  // Exclude the current element
  int ans2 = maximumSumUtil(a, index + 1,
                            count, n);
 
  // Update the maximum ans
  return (dp[index][count] =
          Math.max(ans1, ans2));
}
 
// Function to calculate maximum sum
// of the subsequence obtained
static void maximumSum(int arr[], int N)
{
  // Initialise the dp array with -1
  for(int i = 0; i < 1005; i++)
  {
    for (int j = 0; j < 1005; j++)
    {
      dp[i][j] = -1;
    }
  }
 
  // Print the maximum sum possible
  System.out.print(maximumSumUtil(arr, 0,
                                  1, N - 1));
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array
  int arr[] = {-1, 2, -10, 4, -20};
 
  // Size of the array
  int N = arr.length;
 
  // Function Call
  maximumSum(arr, N);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program for the above approach
 
# Initialize dp array
dp = [[-1 for x in range(1005)]
          for y in range(1005)]
 
# Function to find the maximum
# sum of the subsequence formed
def maximumSumUtil(a, index, count, n):
 
    # Base Case
    if (index > n or count > n + 1):
        return 0
 
    # If already calculated
    # state occurs
    if (dp[index][count] != -1):
        return dp[index][count]
 
    # Include the current element
    ans1 = (maximumSumUtil(a, index + 1,
                              count + 1, n) +
                           a[index] * count)
 
    # Exclude the current element
    ans2 = maximumSumUtil(a, index + 1,
                          count, n)
 
    # Update the maximum ans
    dp[index][count] = max(ans1, ans2)
 
    return dp[index][count]
 
# Function to calculate maximum sum
# of the subsequence obtained
def maximumSum(arr, N):
 
    # Print the maximum sum possible
    print(maximumSumUtil(arr, 0, 1,
                             N - 1))
 
# Driver Code
 
# Given array
arr = [ -1, 2, -10, 4, -20 ]
 
# Size of the array
N = len(arr)
 
# Function call
maximumSum(arr, N)
 
# This code is contributed by Shivam Singh
 
 

C#




// C# program for
// the above approach
using System;
class GFG{
 
// Initialize dp array
static int [,]dp = new int[1005, 1005];
 
// Function to find the maximum
// sum of the subsequence formed
static int maximumSumUtil(int []a, int index,
                          int count, int n)
{
  // Base Case
  if (index > n || count > n + 1)
  {
    return 0;
  }
 
  // If already calculated
  // state occurs
  if (dp[index, count] != -1)
    return dp[index, count];
 
  // Include the current element
  int ans1 = maximumSumUtil(a, index + 1,
                            count + 1, n) +
                            a[index] * count;
 
  // Exclude the current element
  int ans2 = maximumSumUtil(a, index + 1,
                            count, n);
 
  // Update the maximum ans
  return (dp[index, count] =
          Math.Max(ans1, ans2));
}
 
// Function to calculate maximum sum
// of the subsequence obtained
static void maximumSum(int []arr, int N)
{
  // Initialise the dp array with -1
  for(int i = 0; i < 1005; i++)
  {
    for (int j = 0; j < 1005; j++)
    {
      dp[i, j] = -1;
    }
  }
 
  // Print the maximum sum possible
  Console.Write(maximumSumUtil(arr, 0,
                               1, N - 1));
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array
  int []arr = {-1, 2, -10, 4, -20};
 
  // Size of the array
  int N = arr.Length;
 
  // Function Call
  maximumSum(arr, N);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// JavaScript program for
// the above approach
 
// Let initialize dp array
let dp = new Array(1005);
 
// Loop to create 2D array using 1D array
for (var i = 0; i < dp.length; i++) {
    dp[i] = new Array(2);
}
  
// Function to find the maximum
// sum of the subsequence formed
function maximumSumUtil(a, index,
                          count, n)
{
  // Base Case
  if (index > n || count > n + 1)
  {
    return 0;
  }
  
  // If already calculated
  // state occurs
  if (dp[index][count] != -1)
    return dp[index][count];
  
  // Include the current element
  let ans1 = maximumSumUtil(a, index + 1,
                            count + 1, n) +
                            a[index] * count;
  
  // Exclude the current element
  let ans2 = maximumSumUtil(a, index + 1,
                            count, n);
  
  // Update the maximum ans
  return (dp[index][count] =
          Math.max(ans1, ans2));
}
  
// Function to calculate maximum sum
// of the subsequence obtained
function maximumSum(arr, N)
{
  // Initialise the dp array with -1
  for(let i = 0; i < 1005; i++)
  {
    for (let j = 0; j < 1005; j++)
    {
      dp[i][j] = -1;
    }
  }
  
  // Print the maximum sum possible
  document.write(maximumSumUtil(arr, 0,
                                  1, N - 1));
}
 
// Driver code
 
  // Given array
  let arr = [-1, 2, -10, 4, -20];
  
  // Size of the array
  let N = arr.length;
  
  // Function Call
  maximumSum(arr, N);
                             
</script>
 
 
Output: 
15

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

Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memoization(top-down) because memoization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a table DP to store the solution of the subproblems and initialize it with 0.
  • Now Iterate over subproblems to get the value of current problem form previous computation of subproblems stored in DP.
  • Take two variables ans1 and ans2 for two previous computations and get the maximum from them and store in dp  
  • Return the final solution stored in dp[0][1].

Implementation :

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum
// sum of the subsequence formed
int maximumSum(int a[], int n)
{  
     
    // initialize Dp to store computation of subproblems
    int dp[n+1][n+2];
    memset(dp, 0, sizeof(dp));
 
 
    // Traverse the array in reverse order and fill the dp table
    for(int i=n-1; i>=0; i--){
        for(int j=1; j<=n+1; j++){
            // Include the current element
            int ans1 = dp[i+1][j+1] + a[i]*j;
            // Exclude the current element
            int ans2 = dp[i+1][j];
            // Update the maximum ans
            dp[i][j] = max(ans1, ans2);
        }
    }
    // Return the answer
    return dp[0][1];
}
 
int main()
{
    // Given array
    int arr[] = { -1, 2, -10, 4, -20 };
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
    // Function Call
    cout << maximumSum(arr, N);
    return 0;
}
 
// this code is contributed by bhardwajji
 
 

Java




import java.util.Arrays;
 
class Main {
    // Function to find the maximum sum of the subsequence
    // formed
    static int maximumSum(int a[], int n)
    {
        // initialize Dp to store computation of subproblems
        int[][] dp = new int[n + 1][n + 2];
        for (int[] row : dp) {
            Arrays.fill(row, 0);
        }
 
        // Traverse the array in reverse order and fill the
        // dp table
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 1; j <= n + 1; j++) {
                // check if the indices are within bounds
                if (i + 1 < n && j + 1 < n + 2) {
                    // Include the current element
                    int ans1 = dp[i + 1][j + 1] + a[i] * j;
                    // Exclude the current element
                    int ans2 = dp[i + 1][j];
                    // Update the maximum ans
                    dp[i][j] = Math.max(ans1, ans2);
                }
            }
        }
 
        // Return the answer
        return dp[0][1];
    }
 
    public static void main(String[] args)
    {
        // Given array
        int[] arr = { -1, 2, -10, 4, -20 };
        // Size of the array
        int N = arr.length;
        // Function Call
        System.out.println(maximumSum(arr, N));
    }
}
 
 

Python3




def maximumSum(a, n):
   
    # initialize dp to store computation of subproblems
    dp = [[0] * (n+2) for _ in range(n+1)]
     
    # Traverse the array in reverse order and fill the dp table
    for i in range(n-1, -1, -1):
        for j in range(1, n+2):
           
            # check if the indices are within bounds
            if i+1 < n and j+1 < n+2:
               
                # Include the current element
                ans1 = dp[i+1][j+1] + a[i] * j
                 
                # Exclude the current element
                ans2 = dp[i+1][j]
                 
                # Update the maximum ans
                dp[i][j] = max(ans1, ans2)
     
    # Return the answer
    return dp[0][1]
 
# Given array
arr = [-1, 2, -10, 4, -20]
# Size of the array
N = len(arr)
 
# Function call
print(maximumSum(arr, N))
 
 

C#




using System;
 
class MainClass {
    // Function to find the maximum sum of the subsequence
    // formed
    static int maximumSum(int[] a, int n)
    {
        // initialize Dp to store computation of subproblems
        int[][] dp = new int[n + 1][];
        for (int i = 0; i < dp.Length; i++) {
            dp[i] = new int[n + 2];
            for (int j = 0; j < dp[i].Length; j++) {
                dp[i][j] = 0;
            }
        }
 
        // Traverse the array in reverse order and fill the
        // dp table
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 1; j <= n + 1; j++) {
                // check if the indices are within bounds
                if (i + 1 < n && j + 1 < n + 2) {
                    // Include the current element
                    int ans1 = dp[i + 1][j + 1] + a[i] * j;
                    // Exclude the current element
                    int ans2 = dp[i + 1][j];
                    // Update the maximum ans
                    dp[i][j] = Math.Max(ans1, ans2);
                }
            }
        }
 
        // Return the answer
        return dp[0][1];
    }
 
    public static void Main(string[] args)
    {
        // Given array
        int[] arr = { -1, 2, -10, 4, -20 };
        // Size of the array
        int N = arr.Length;
        // Function Call
        Console.WriteLine(maximumSum(arr, N));
    }
}
 
 

Javascript




// JavaScript program for above approach
 
// Function to find the maximum
// sum of the subsequence formed
function maximumSum(a, n)
{  
    // initialize Dp to store computation of subproblems
    let dp = new Array(n+1).fill(0).map(() => new Array(n+2).fill(0));
 
    // Traverse the array in reverse order and fill the dp table
    for(let i=n-1; i>=0; i--)
    {
        for(let j=1; j<=n+1; j++)
        {
            // Include the current element
            let ans1 = dp[i+1][j+1] + a[i]*j;
             
            // Exclude the current element
            let ans2 = dp[i+1][j];
             
            // Update the maximum ans
            dp[i][j] = Math.max(ans1, ans2);
        }
    }
     
    // Return the answer
    return dp[0][1];
}
 
// Given array
let arr = [ -1, 2, -10, 4, -20 ];
 
// Size of the array
let N = arr.length;
 
// Function Call
console.log(maximumSum(arr, N));
 
 

Output

15

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



Next Article
Maximum sum subsequence of length K | Set 2
https://media.geeksforgeeks.org/auth/avatar.png
Anonymous
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • Experiences
  • Interview Experiences
  • Mathematical
  • Recursion
  • subsequence
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Mathematical
  • Recursion

Similar Reads

  • Maximize XOR subsequence possible by equidistant elements from both ends
    Given an array A[] of size N, find the Maximum Xor Subsequence such that both A [ i ] and A [ N - i - 1 ] belong to this subsequence, where i ranges between [0, N - 1]. Examples: Input: N = 8, A [ ] = {1, 2, 3, 4, 5, 6, 7, 8}Output: 13Explanation:Maximum Xor Subsequence is {1, 3, 4, 5, 6, 8} Input:
    15+ min read
  • Maximum sum increasing subsequence from a prefix and a given element after prefix is must
    Given an array of n positive integers, write a program to find the maximum sum of increasing subsequence from prefix till ith index and also including a given kth element which is after i, i.e., k > i. Examples : Input: arr[] = {1, 101, 2, 3, 100, 4, 5} i-th index = 4 (Element at 4th index is 100
    14 min read
  • Find maximum sum of subsequence after flipping signs of at most K elements in given Array
    Given an array arr, the task is to find the maximum sum of subsequence after flipping signs of at most K elements. Examples: Input: arr = [6, -10, -1, 0, -4, 2], K = 2Output: 22Explanation: Maximum sum can be obtained by flipping -10 and -4 to 10 and 4 respectively Input: arr = [1, 2, 3], K = 3Outpu
    6 min read
  • Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence
    Given an array arr[] consisting of N positive integers, the task is to find the maximum sum of subsequences from the given array such that elements in the subsequence are assigned positive and negative signs alternately. Subsequence = {a, b, c, d, e, ... }, Sum of the above subsequence = (a - b + c
    12 min read
  • Maximum sum subsequence of length K | Set 2
    Given an array sequence arr[] i.e [A1, A2 …An] and an integer k, the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3………<=Sk. Examples: Input: arr[] = {-1, 3, 4, 2, 5}, K = 3Output: 3 4 5Explanation: Subsequence 3 4 5 with sum 12 is the s
    7 min read
  • Find heaviest increasing Subsequence with maximum sum in a String
    Given a string s and an array arr[] representing the weights of each character in the string, the task is to find the heaviest increasing subsequence with the maximum sum and return that subsequence. Examples: Input: s = "acbde", arr[] = {2, 4, 3, 5, 1}Output: acdExplanation: The heaviest increasing
    8 min read
  • Maximize subsequence sum after putting plus minus sign alternatively on elements
    Given an array arr[] of size N. The task is to find the maximum score that can be achieved by alternative minus - plus of elements of any subsequence in the array. Example: Input: arr[] = {2, 3, 6, 5, 4, 7, 8}, N = 7Output: 10Explanation: Pick the sequence as {2, 3, 6, 5, 4, 7, 8} = {6, 4, 8}. So, a
    5 min read
  • Reduce given Array to 0 by maximising sum of chosen elements
    Given an array arr[] containing N positive integers, the task is to maximize the array sum when after every sum operation all the remaining array elements decrease by 1. Note: The value of an array element does not go below 0. Examples: Input: arr[] = {6, 2, 4, 5} Output: 12 Explanation: Add 6 initi
    9 min read
  • Minimize subsequence multiplication to convert Array sum to be power of 2
    Given an array A[] of size N such that every element is a positive power of 2. In one operation, choose a non-empty subsequence of the array and multiply all the elements of the subsequence with any positive integer such that the sum of the array becomes a power of 2. The task is to minimize this op
    6 min read
  • Maximum sum subsequence of any size which is decreasing-increasing alternatively
    Given an array of integers arr[], find the subsequence with maximum sum whose elements are first decreasing, then increasing, or vice versa, The subsequence can start anywhere in the main sequence, not necessarily at the first element of the main sequence. A sequence {x1, x2, .. xn} is an alternatin
    15+ 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