ในปัญหานี้ เราได้รับสตริงที่แสดงถึงตัวเลข งานของเราคือสร้างโปรแกรมเพื่อค้นหาผลรวมสูงสุดและผลิตภัณฑ์ของหลัก M เรียงกันเป็นตัวเลขในภาษา C++
คำอธิบายปัญหา
เราพบลำดับทั้งหมดของตัวเลข M ที่ต่อเนื่องกัน และคืนยอดรวมและผลิตภัณฑ์สูงสุด
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
number = 2379641, M = 4
ผลลัพธ์
maxSum = 26maxProd = 1512
คำอธิบาย
ลำดับย่อยทั้งหมดของขนาด 4 คือ 2379, 3796, 7964, 9641 maxSum =7 + 9 + 6 + 4 =26 maxProd =7 * 9 * 6 * 4 =1512
แนวทางการแก้ปัญหา
วิธีแก้ปัญหาอย่างง่ายคือค้นหาลำดับย่อยที่เป็นไปได้ต่อเนื่องกันของขนาด M จากตัวเลข จากนั้นบวกและคูณค่าทั้งหมดของจำนวนเต็ม จากนั้นคืนค่าสูงสุดของผลรวมและมูลค่าผลิตภัณฑ์ทั้งหมด
ตัวอย่าง
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
#include <iostream>
using namespace std;
int findMaxVal(int x, int y){
if(x > y)
return x;
return y;
}
void calcMaxProductAndSum(string number, int M){
int N = number.length();
int maxProd = -1, maxSum = -1;
int product = 1, sum = 0;
for (int i = 0; i < N - M; i++){
product = 1, sum = 0;
for (int j = i; j < M + i; j++){
product = product * (number[j] - '0');
sum = sum + (number[j] - '0');
}
maxProd = findMaxVal(maxProd, product);
maxSum = findMaxVal(maxSum, sum);
}
cout<<"The Maximum Product of "<<M<<" consecutive digits in number "<<number<<" is "<<maxProd<<endl;
cout<<"The Sum Product of "<<M<<" consecutive digits in number "<<number<<" is "<<maxSum;
}
int main() {
string str = "2379641";
int m = 4;
calcMaxProductAndSum(str, m);
} ผลลัพธ์
The Maximum Product of 4 consecutive digits in number 2379641 is 1512 The Sum Product of 4 consecutive digits in number 2379641 is 26