C++中求數字M個連續數字的最大和與積
本文給定一個表示數字的字串。我們的任務是建立一個C++程式,找出給定數字中M個連續數字的最大和與積。我們找到所有長度為M的連續數字序列,並返回最大和與積。
在數學中,**連續數字**定義為按從小到大的順序排列的數字,中間沒有缺失的數字。
這個問題可以透過遍歷數字的字串表示來解決,換句話說,我們考慮長度為M的連續片段,計算片段中數字的和與積。
我們將始終檢查之前遇到的最大和與最大積。如果我們迴圈遍歷整個字串,我們將得到M個連續數字的最大和與最大積。
**M個連續數字的最大和:**因此,各方應盡最大努力,如果可能,遍歷M個連續數字的整個範圍,其和是所有M位數序列中的最大值。
**M個連續數字的最大積:**同樣地,它透過識別數字中積最大的M個數字來找到最大M位數組合。
讓我們來看一下**輸入和輸出場景**,瞭解輸入值如何與所需輸出相關聯:
輸入
number = 2379641, M = 4
輸出
maxSum = 26 maxProd = 1512
解釋
這些都是給定的長度為4的子序列:2379, 3796, 7964, 和 9641。
最大和 = 7 + 9 + 6 + 4 = 26
最大積 = 7 * 9 * 6 * 4 = 1512
解決方案方法
解決這個問題的一個簡單方法是從數字中找到所有可能的長度為M的連續子序列,然後將所有整數的值相加和相乘,並返回所有和與積值中的最大值。
示例
以下是C++程式,用於查詢數字中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; int 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 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 of 4 consecutive digits in number 2379641 is: 26
廣告