Mô tả bài toán
Cho chuỗi ký tự đại diện cho một số và số nguyên M. Tìm tổng và tích lớn nhất của M chữ số liên tiếp bất kỳ trong số đó.
Ví dụ: number = "2379641", M = 4 → Các dãy 4 chữ số: 2379, 3796, 7964, 9641. Tổng max = 7+9+6+4 = 26. Tích max = 7×9×6×4 = 1512.
Giải pháp (Cửa sổ trượt)
- Duyệt mọi vị trí bắt đầu
itừ 0 đếnN-M. - Tính tổng và tích của
Mchữ số từiđếni+M-1. - Cập nhật
maxSumvàmaxProd.
Ví dụ minh họa
#include <iostream>
using namespace std;
int findMaxVal(int x, int y) { return x > y ? x : y; }
void calcMaxProductAndSum(string number, int M) {
int N = number.length();
int maxProd = -1, maxSum = -1;
for (int i = 0; i <= N - M; i++) {
int product = 1, sum = 0;
for (int j = i; j < i + M; j++) {
product *= (number[j] - '0');
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);
return 0;
}
Đầu ra
The Maximum Product of 4 consecutive digits in number 2379641 is 1512 The Sum Product of 4 consecutive digits in number 2379641 is 26