すべてのチャレンジ
中級 1件解決済み 正答率100.0%

Largest Adjacent-Digit Product

Take every contiguous window of span digits and multiply its digits.

このチャレンジで学べること

  • Examine every window of a fixed size
  • Multiply digits inside a window
  • Track the best product

問題

翻訳を表示

Take every contiguous window of span digits and multiply its digits. Return the largest product. Leading zeros are ordinary digits; a window containing zero has product zero. Do not reorder or skip digits.

Implement largest_adjacent_digit_product(digits, span).

Input

digits: The digit sequence, including any leading zeros.

span: The exact number of adjacent digits in a window.

Output

Return the greatest product over all windows of this width.

制約

1 ≤ digit-string length ≤ 100,000. Characters are 0…9. 1 ≤ span ≤ min(18, length). All products fit signed 64-bit.

例

例 1
入力:
digits = "23405"
span = 2

期待される出力:
expected = 12
入力:
std::string digits = "23405";
long long span = 2;

期待される出力:
long long expected = 12;
入力:
string digits = "23405";
long span = 2;

期待される出力:
long expected = 12;

解説

The windows 23, 34, 40, and 05 have products 6, 12, 0, and 0. The largest is 12.

例 2
入力:
digits = "102"
span = 3

期待される出力:
expected = 0
入力:
std::string digits = "102";
long long span = 3;

期待される出力:
long long expected = 0;
入力:
string digits = "102";
long span = 3;

期待される出力:
long expected = 0;

解説

There is only one width-three window. It contains zero, so 1 × 0 × 2 = 0.

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

A zero inside a window forces that product to zero, so only contiguous nonzero stretches can contribute to the maximum.

ヒント 2

Use a sliding window or track products across runs of digits to avoid recomputing every span from scratch.

ヒント 3

Watch the exact span requirement: leading zeros count as digits, and if span exceeds a nonzero block, the product is zero.

目安の計算量

O(n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 975 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。