Maximum Balanced Subsequence Score
Last Updated : 23 Jul, 2024
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).
Time Complexity: O(n)
Auxiliary Space: O(n)
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