Maximum Product
Pista
Si , ¿cuál será siempre la mejor solución?
Explicación
Empecemos con un ejemplo: y . Obsérvese que realmente hay que considerar tres números como respuestas viables: , y . ¡Hay que pensar por qué, y cómo se generaliza esto!
Podemos aplicar un enfoque muy similar cuando . De hecho, es casi idéntico, con una diferencia menor. Consideremos el caso en que y , igual que antes. La única diferencia es que ya no podemos considerar como respuesta viable, porque es menor que . De nuevo, ¡hay que pensar cómo generalizar esto!
Implementación
Complejidad temporal: , donde es el número máximo de dígitos (19).
#include <bits/stdc++.h>
using ll = long long;
using namespace std;
/** @return the product of the given string's digits (-1 if empty) */
ll prod(string s) {
// remove leading zeros
int i = 0;
while (s[i] == '0') { i++; }
s = s.substr(i);
if (!s.length()) { return -1; }
ll res = 1;
for (char c : s) { res *= c - '0'; }
return res;
}
int main() {
string l, r;
cin >> l >> r;
// pad beginning of l with zeros
// l = 12, r = 132 -> l = 012, r = 132
while (l.length() < r.length()) { l.insert(l.begin(), '0'); }
string ans = "";
// i -> length of LCP (longest common prefix) of str and r
bool eq = true; // whether l[0, i) = r[0, i)
for (int i = 0; i <= r.length(); i++) {
string cur = r.substr(0, i);
eq = eq && l[i] == r[i];
/*
* in this case, str[i] must equal r[i]
* and now the shared prefix has length i + 1
* which contradicts our assumption that the LCP has length i
*/
if (i < r.length() && eq) { continue; }
if (i < r.length()) { cur += char(r[i] - 1); }
// fill remaining digits with 9's
cur += string(r.length() - cur.length(), '9');
if (prod(cur) > prod(ans)) { ans = cur; }
}
// remove any leading zeros from ans
while (ans[0] == '0') { ans.erase(ans.begin()); }
cout << ans << endl;
}