bluecode-最大乘积问题

26 阅读2分钟

问题描述

小R最近遇到了一个数组问题。他有一个包含 NN 个元素的数组,记作 a1,a2,...,aNa1​,a2​,...,aN​。为了分析这个数组的特性,小R定义了两个函数 L(i)L(i) 和 R(i)R(i),并希望通过这两个函数来找到一些有趣的结论。

  • L(i)L(i) 是满足以下条件的最大的 jj 值:
  • j<ij<i
  • a[j]>a[i]a[j]>a[i]
  • 如果找不到这样的 jj,那么 L(i)=0L(i)=0;如果有多个满足条件的 jj,选择离 ii 最近的那个。
  • R(i)R(i) 是满足以下条件的最小的 kk 值:
  • k>ik>i
  • a[k]>a[i]a[k]>a[i]
  • 如果找不到这样的 kk,那么 R(i)=0R(i)=0;如果有多个满足条件的 kk,选择离 ii 最近的那个。

最终,小R定义 MAX(i)=L(i)∗R(i)MAX(i)=L(i)∗R(i),他想知道在 1≤i≤N1≤i≤N 的范围内,MAX(i)MAX(i) 的最大值是多少。


测试样例

样例1:

输入:n = 5, array = [5, 4, 3, 4, 5]
输出:8

样例2:

输入:n = 6, array = [2, 1, 4, 3, 6, 5]
输出:15

样例3:

输入:n = 7, array = [1, 2, 3, 4, 5, 6, 7]
输出:0

#include <algorithm>
#include <iostream>
#include <stack>
#include <vector>

using namespace std;

int solution(int n, std::vector<int> array) {
  vector<int> left(n, 0);
  vector<int> right(n, 0);
  stack<int> st;

  // Calculate left[i]: first greater element to the left
  for (int i = 0; i < n; ++i) {
    while (!st.empty() && array[st.top()] <= array[i]) {
      st.pop();
    }
    if (!st.empty()) {
      left[i] = st.top() + 1; // 1-based index
    } else {
      left[i] = 0;
    }
    st.push(i);
  }

  // Clear the stack for reuse
  while (!st.empty()) {
    st.pop();
  }

  // Calculate right[i]: first greater element to the right
  for (int i = n - 1; i >= 0; --i) {
    while (!st.empty() && array[st.top()] <= array[i]) {
      st.pop();
    }
    if (!st.empty()) {
      right[i] = st.top() + 1; // 1-based index
    } else {
      right[i] = 0;
    }
    st.push(i);
  }

  // Calculate the maximum product
  int max_val = 0;
  for (int i = 0; i < n; ++i) {
    max_val = max(max_val, left[i] * right[i]);
  }

  return max_val;
}

int main() {
  // Add your test cases here

  std::cout << (solution(5, {5, 4, 3, 4, 5}) == 8) << std::endl;
  return 0;
}