Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Maximum Balanced Subsequence Score
Next article icon

Maximum Balanced Subsequence Score

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a stock's prices for the past n days in the array stockPrice. Choose a subsequence (an ordered subset of an array's elements) of stock prices, called chosenDays, such that the chosen subsequence of stock prices is balanced. The score of the chosen subsequence is the sum of stock prices on the chosen days. Find the maximum possible score that can be obtained by choosing an optimally balanced subsequence. The subsequence of stock prices is balanced if the following condition holds, stockPrice[chosenDays[i]]-stockPrice[chosenDays[i-1]] = chosenDays[i]-chosenDays[i - 1], for i > 0.

Examples:

Input: n = 5, stockPrice = [1, 5, 3, 7, 8]
Output: 20
Explanation:The subsequence [5, 7, 8] can be chosen. Corresponding chosen days are [1, 3, 4] (considering 0-based indexing). Now,
• stockPrice[3] - stockPrice[1] = 7 - 5 = 2 and 3 - 1 = 2
• stockPrice[4] - stockPrice[3]= 8 - 7 = 1 and 4 - 3 = 1
Thus, the subsequence is balanced. Score= 5 + 7 + 8 = 20
The subsequence [1, 3] can be chosen. Corresponding chosen days are [0, 2] (considering 0-based indexing). Now,
• stockPrice[2] - stockPrice[0] = 3 - 1 = 2 and 2 - 0 = 2
Thus, the subsequence is balanced. Score= 1 + 3 = 4
20 is maximum possible. So, the answer is 20.

Input: n = 3, stockPrice = [1, 2, 3]
Output: 6
Explanation:The subsequence [1, 2, 3] can be chosen. Corresponding chosen days are [0, 1, 2] (considering 0-based indexing). Now,
• stockPrice[1] - stockPrice[0]= 2 - 1= 1 and 1 - 0 = 1
• stockPrice[2] - stockPrice[1]= 3 - 2 = 1 and 2 - 1 = 1
Thus, the subsequence is balanced. Score= 1 + 2 + 3 = 6
6 is maximum possible. So, the answer is 6.

Approach: To solve the problem follow the idea below:

Idea: The given equation can be reformulated as:
• stockPrice[chosenDays[i]] - chosenDays[i] = stockPrice[chosenDays[i-1]] - chosenDays[i-1]
This means that we can group elements together if the difference between their stock price and their index is the same.For example, in the given input 1, the elements 5, 7, and 8 can be grouped together because:
• 5 - 1 = 4
• 7 - 3 = 4
• 8 - 4 = 4
In other words, the solution works by finding the "gaps" between the stock prices. If two stock prices have the same gap, then they can be grouped together in a balanced subsequence. Now the problem is just reduced to storing the sum of elements corresponding to the gap.

Steps to solve the problem:

  • Create a map mp.
  • Store the difference between the stock price and the index for each element in diff.
  • Store cumulative stock prices for each unique difference between stock prices and their positions.
  • Iterate through the map mp to find the maximum cumulative stock price among all the balanced subsequences.
  • Update the maxm variable if it finds a higher cumulative stock price.
  • Return the maximum cumulative stock price stored in maxm, which is the result.

Below is the code for the above approach:

C++14
// C++ Code for the above approach: #include <bits/stdc++.h> using namespace std;  long long MaxBalancedSubsequenceScore(int n, vector<int>& stockPrice) {      // Create an unordered map to store     // the difference and cumulative     // stock prices     unordered_map<int, long long> mp;     long long maxm = 0;     for (int i = 0; i < n; i++) {          // Calculate the difference between         // stock price and index         int diff = stockPrice[i] - i;          // Add the stock price to         // the corresponding difference         mp[diff] += stockPrice[i];     }      // Find the maximum score     // by iterating through the map     for (auto it : mp) {         if (it.second > maxm) {              // Update the maximum score             // if a higher score is found             maxm = it.second;         }     }     // Return the maximum score     return maxm; }  // Driver code int main() {     vector<int> stockPrice{ 1, 5, 3, 7, 8 };     // Function Call     cout << MaxBalancedSubsequenceScore(stockPrice.size(),                                         stockPrice)          << endl;     stockPrice = { 1, 2, 3 };      // Function Call     cout << MaxBalancedSubsequenceScore(stockPrice.size(),                                         stockPrice)          << endl;     return 0; } 
Java
// Java Code import java.util.*;  public class MaxBalancedSubsequenceScore {     public static long getMaximumScore(int n,                                        int[] stockPrice)     {         // Create a HashMap to store+         // the difference and cumulative stock prices         Map<Integer, Long> map = new HashMap<>();         long maxm = 0;         for (int i = 0; i < n; i++) {             // Calculate the difference             // between stock price and index             int diff = stockPrice[i] - i;              // Add the stock price to             // the corresponding difference             if (map.containsKey(diff)) {                 map.put(diff,                         map.get(diff) + stockPrice[i]);             }             else {                 map.put(diff, (long)stockPrice[i]);             }         }         // Find the maximum score         // by iterating through the map         for (Map.Entry<Integer, Long> entry :              map.entrySet()) {             if (entry.getValue() > maxm) {                 // Update the maximum score                 // if a higher score is found                 maxm = entry.getValue();             }         }         // Return the maximum score         return maxm;     }      // Driver code     public static void main(String[] args)     {         int[] stockPrice1 = { 1, 5, 3, 7, 8 };         // Function Call         System.out.println(getMaximumScore(             stockPrice1.length, stockPrice1));         int[] stockPrice2 = { 1, 2, 3 };         // Function Call         System.out.println(getMaximumScore(             stockPrice2.length, stockPrice2));     } } 
Python
# Python Code def MaxBalancedSubsequenceScore(n, stockPrice):     # Create a dictionary to store     # the difference and cumulative stock prices     mp = {}     maxm = 0     for i in range(n):         # Calculate the difference         #  between stock price and index         diff = stockPrice[i] - i          # Add the stock price to         #  the corresponding difference         if diff in mp:             mp[diff] += stockPrice[i]         else:             mp[diff] = stockPrice[i]      # Find the maximum score     #  by iterating through the dictionary     for key, value in mp.items():         if value > maxm:             # Update the maximum score             #  if a higher score is found             maxm = value      # Return the maximum score     return maxm   # Driver code stockPrice1 = [1, 5, 3, 7, 8] # Function Call print(MaxBalancedSubsequenceScore(len(stockPrice1), stockPrice1)) stockPrice2 = [1, 2, 3] # Function Call print(MaxBalancedSubsequenceScore(len(stockPrice2), stockPrice2)) 
C#
using System; using System.Collections.Generic;  class Program {     static long     MaxBalancedSubsequenceScore(int n, List<int> stockPrice)     {         // Create a dictionary to store the difference and         // cumulative stock prices         Dictionary<int, long> dict             = new Dictionary<int, long>();         long maxm = 0;          for (int i = 0; i < n; i++) {             // Calculate the difference between stock price             // and index             int diff = stockPrice[i] - i;              // Add the stock price to the corresponding             // difference             if (dict.ContainsKey(diff))                 dict[diff] += stockPrice[i];             else                 dict.Add(diff, stockPrice[i]);         }          // Find the maximum score by iterating through the         // dictionary         foreach(var kvp in dict)         {             if (kvp.Value > maxm) {                 // Update the maximum score if a higher                 // score is found                 maxm = kvp.Value;             }         }          // Return the maximum score         return maxm;     }      // Driver code     static void Main()     {         List<int> stockPrice             = new List<int>{ 1, 5, 3, 7, 8 };         // Function Call         Console.WriteLine(MaxBalancedSubsequenceScore(             stockPrice.Count, stockPrice));          stockPrice = new List<int>{ 1, 2, 3 };         // Function Call         Console.WriteLine(MaxBalancedSubsequenceScore(             stockPrice.Count, stockPrice));     } } 
JavaScript
// JavaScript code for the above approach  function maxBalancedSubsequenceScore(n, stockPrice) {     // Create an object to store the difference and cumulative stock prices     let mp = {};     let maxm = 0;      for (let i = 0; i < n; i++) {         // Calculate the difference between stock price and index         const diff = stockPrice[i] - i;          // Add the stock price to the corresponding difference         mp[diff] = (mp[diff] || 0) + stockPrice[i];     }      // Find the maximum score by iterating through the object     for (const key in mp) {         if (mp.hasOwnProperty(key) && mp[key] > maxm) {             // Update the maximum score if a higher score is found             maxm = mp[key];         }     }      // Return the maximum score     return maxm; }  // Driver code const stockPrice1 = [1, 5, 3, 7, 8]; console.log(maxBalancedSubsequenceScore(stockPrice1.length, stockPrice1));  const stockPrice2 = [1, 2, 3]; console.log(maxBalancedSubsequenceScore(stockPrice2.length, stockPrice2));  // This code is contributed by Abhinav Mahajan (abhinav_m22). 

Output
20 6 

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


Next Article
Maximum Balanced Subsequence Score

A

abhishek9202
Improve
Article Tags :
  • Mathematical
  • Geeks Premier League
  • DSA
  • cpp-unordered_map
  • Java-HashMap
  • Atlassian
  • Python dictionary-programs
  • top-dsa-problems
  • Geeks Premier League 2023
Practice Tags :
  • Atlassian
  • Mathematical

Similar Reads

    Maximum sum alternating subsequence
    Given an array, the task is to find sum of maximum sum alternating subsequence starting with first element. Here alternating sequence means first decreasing, then increasing, then decreasing, ... For example 10, 5, 14, 3 is an alternating sequence. Note that the reverse type of sequence (increasing
    13 min read
    Maximum Sum Subsequence of length k
    Given an array sequence [A1, A2 ...An], the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3.........<=Sk. Examples: Input : n = 8 k = 3 A=[8 5 9 10 5 6 21 8] Output : 40 Possible Increasing subsequence of Length 3 with maximum possible s
    11 min read
    Maximum Sum Increasing Subsequence
    Given an array arr[] of n positive integers. The task is to find the sum of the maximum sum subsequence of the given array such that the integers in the subsequence are sorted in strictly increasing order.Examples:Input: arr[] = [1, 101, 2, 3, 100]Output: 106Explanation: The maximum sum of a increas
    15+ min read
    Maximum Sum Subsequence
    Given an array arr[] of size N, the task is to find the maximum sum non-empty subsequence present in the given array. Examples: Input: arr[] = { 2, 3, 7, 1, 9 } Output: 22 Explanation: Sum of the subsequence { arr[0], arr[1], arr[2], arr[3], arr[4] } is equal to 22, which is the maximum possible sum
    5 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
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