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++ 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 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 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))
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 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)