Skip to content

2898. Maximum Linear Stock Score 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  long long maxScore(vector<int>& prices) {
    //    prices[indexes[j]] - prices[indexes[j - 1]]
    // == indexes[j] - indexes[j - 1]
    //    prices[indexes[j]] - indexes[j]
    // == prices[indexes[j - 1]] - indexes[j - 1]
    //
    // So, elements in the same subsequence must have the same prices[i] - i.
    unordered_map<int, long> groupIdToSum;

    for (int i = 0; i < prices.size(); ++i)
      groupIdToSum[prices[i] - i] += prices[i];

    return ranges::max_element(groupIdToSum,
                               [](const std::pair<int, long>& p1,
                                  const std::pair<int, long>& p2) {
      return p1.second < p2.second;
    })->second;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public long maxScore(int[] prices) {
    //    prices[indexes[j]] - prices[indexes[j - 1]]
    // == indexes[j] - indexes[j - 1]
    //    prices[indexes[j]] - indexes[j]
    // == prices[indexes[j - 1]] - indexes[j - 1]
    //
    // So, elements in the same subsequence must have the same prices[i] - i.
    Map<Integer, Long> groupIdToSum = new HashMap<>();

    for (int i = 0; i < prices.length; ++i)
      groupIdToSum.merge(prices[i] - i, (long) prices[i], Long::sum);

    return groupIdToSum.values().stream().max(Long::compare).orElse(0L);
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def maxScore(self, prices: list[int]) -> int:
    groupIdToSum = collections.defaultdict(int)

    for i, price in enumerate(prices):
      groupIdToSum[price - i] += price

    return max(groupIdToSum.values())