I treated it too difficult.. nothing special, just some optimization mentioned as:
http://saraguru.weebly.com/how-i-solved/find-maximum-index-product-hackerrank
#include <cmath> #include <cstdio> #include <vector> #include <map> #include <set> #include <unordered_set> #include <string> #include <iostream> #include <algorithm> using namespace std; int main() { int n; cin >> n; vector<int> in; for (int i = 0; i < n; i++) { int tmp; cin >> tmp; in.push_back(tmp); } vector<int> left(n, 0); for (int i = 1; i < n; i++) { if (in[i] == in[i-1]) { left[i] = left[i - 1]; } else if (in[i] < in[i - 1]) { left[i] = i; } else if (in[i] > in[i - 1]) { int j = left[i - 1]; while (j >= 0) { if (in[j] > in[i]) { left[i] = j + 1; break; } j--; } } } vector<int> right(n, 0); for (int i = n - 2; i >= 0; i--) { if (in[i] == in[i + 1]) { right[i] = right[i + 1]; } else if (in[i] < in[i + 1]) { right[i] = i + 1 + 1; } else if (in[i] > in[i + 1]) { int j = right[i + 1]; while (j < n) { if (in[j] > in[i]) { right[i] = j + 1; break; } j++; } } } // get long long ret = 0; for (int i = 1; i < n - 1; i++) { ret = std::max(ret, (long long)left[i] * (long long)right[i]); } cout << ret << endl; return 0; }