ปานกลาง 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Largest Adjacent-Digit Product

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

สิ่งที่คุณจะได้เรียนรู้

  • ตรวจทุกหน้าต่างขนาดคงที่
  • คูณหลักในหน้าต่าง
  • ติดตามผลคูณที่ดีที่สุด

โจทย์

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
อินพุต:
span = 2
digits = "23405"

ผลลัพธ์ที่คาดหวัง:
expected = 12
อินพุต:
long long span = 2;
std::string digits = "23405";

ผลลัพธ์ที่คาดหวัง:
long long expected = 12;
อินพุต:
long span = 2;
string digits = "23405";

ผลลัพธ์ที่คาดหวัง:
long expected = 12;

คำอธิบาย

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

ตัวอย่างที่ 2
อินพุต:
span = 3
digits = "102"

ผลลัพธ์ที่คาดหวัง:
expected = 0
อินพุต:
long long span = 3;
std::string digits = "102";

ผลลัพธ์ที่คาดหวัง:
long long expected = 0;
อินพุต:
long span = 3;
string digits = "102";

ผลลัพธ์ที่คาดหวัง:
long expected = 0;

คำอธิบาย

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

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

ถ้ามีเลข 0 อยู่ในหน้าต่าง ผลคูณจะเป็น 0 ดังนั้นเฉพาะช่วงเลขไม่เป็นศูนย์ที่ติดกันเท่านั้นที่ทำให้ค่าสูงสุดได้

คำใบ้ 2

ใช้ sliding window หรือคำนวณผลคูณตามช่วงของตัวเลขเพื่อลดการคำนวณซ้ำทุกช่วงจากศูนย์

คำใบ้ 3

ระวังขนาดช่วงที่กำหนด: ศูนย์นำหน้านับเป็นหลัก และถ้าช่วงยาวเกินบล็อกที่ไม่มีศูนย์ ผลคูณจะเป็น 0

ความซับซ้อนที่คาดหวัง

เวลา O(n), หน่วยความจำเพิ่ม O(1)

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก