Find the product of the last k numbers in the running stream/in the given array.
Example:
Input: arr={2,0,3,5,4}, k=2
Output: 20
Approach
Java
import java.util.ArrayList;import java.util.List;public class ProductLastKNum {public static void main(String[] args) {int arr[] = { 3, 0, 2, 5, 4 };v = new ArrayList<Integer>();prod = new ArrayList<Integer>();for (int i = 0; i < arr.length; i++)add(arr[i]);System.out.println(getProduct(2));}static List<Integer> v;static List<Integer> prod;static int getProduct(int k) {if (prod.size() < k)return 0;if (prod.size() == k)return prod.get(k - 1);elsereturn prod.get(prod.size() - 1) / prod.get(prod.size() - k - 1);}static void add(int num) {v.add(num);if (prod.size() == 0) {if (num > 0)prod.add(num);} else {if (num > 0)prod.add(prod.get(prod.size() - 1) * num);elseprod = new ArrayList<Integer>();}}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> v, prod;void add(int num){v.push_back(num);if (prod.size() == 0){if (num > 0)prod.push_back(num);}else{if (num > 0)prod.push_back(prod[prod.size() - 1] * num);elseprod.clear();}}int getProduct(int k){if (prod.size() < k)return 0;if (prod.size() == k)return prod[k - 1];elsereturn prod[prod.size() - 1] / prod[prod.size() - k - 1];}int main(){v.clear();prod.clear();int arr[]={3,0,2,5,4};int n=sizeof(arr)/sizeof(arr[0]);for(int i=0;i<n;i++)add(arr[i]);cout << getProduct(2);return 0;}
No comments:
Post a Comment