Tất cả thử thách
Trung bình 1 người đã giải Tỷ lệ chấp nhận 100.0%

Largest Adjacent-Digit Product

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
digits = "23405"
span = 2

Kết quả mong đợi:
expected = 12
Đầu vào:
std::string digits = "23405";
long long span = 2;

Kết quả mong đợi:
long long expected = 12;
Đầu vào:
string digits = "23405";
long span = 2;

Kết quả mong đợi:
long expected = 12;

Giải thích

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

Ví dụ 2
Đầu vào:
digits = "102"
span = 3

Kết quả mong đợi:
expected = 0
Đầu vào:
std::string digits = "102";
long long span = 3;

Kết quả mong đợi:
long long expected = 0;
Đầu vào:
string digits = "102";
long span = 3;

Kết quả mong đợi:
long expected = 0;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 975 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.