Find the largest product of k consecutive digits in N digit number.
Example 1:
Input: n=10, k= 5,str="3675356291" Output: 3150
Approach:
Java
public class LargestProductinSeries {
public static void main(String[] args) {
int n = 10, k = 5;
// string of length n
String str = "3675356291";
System.out.println(maxProduct(n, str, k));
}
// method to find the maximum
// product of the subarray of
// length k
private static int maxProduct(int n, String str, int k) {
int arr[] = new int[n];
// convert string into array
// with each digit
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(
String.valueOf(str.charAt(i)));
int ans = 0;
// Iterate till their is
// subarray of length k
// Possible
for (int i = 0; i <= n - k; i++) {
int prod = 1;
// iterate till the k
for (int j = 0; j < k; j++) {
prod = prod * arr[i + j];
}
// update ans
ans = Math.max(ans, prod);
}
return ans;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the maximum
//product of the subarray of
//length k
int maxProduct(int n,string str,int k)
{
int arr[n];
//convert string into array
//with each digit
for(int i=0;i<n;i++)
arr[i]=str[i]-'0';
int ans=0;
//itearte till thier is
//subarray of length k
//posible
for(int i=0;i<=n-k;i++)
{
int prod=1;
//iterate till the k
for(int j=0;j<k;j++)
{
prod=prod*arr[i+j];
}
//update ans
ans=max(ans,prod);
}
return ans;
}
int main()
{
int n=10,k=5;
int prod=1;
//string of length n
string str="3675356291";
cout<<maxProduct(n,str,k);
return 0;
}
No comments:
Post a Comment