Input example: 1 2 3 4 5 (array elements) m = 1 (Odd numbers) Output example: 8 . Subarrays are [ [1] , [1,2] , [2,3] , [2,3,4] , [3] , [3,4] , [4,5] , [5] ]
Here is my implementation. In the worst case, this will take O (n + n ^ 2). Are there ways to optimize this code?
int main() { int n, *a, count1=0, m, *dp; cin>>n; a = new int[n]; dp =new int[n]; for(int i=0; i<n; i++) { cin >> a[i]; } cin >> m; for(int i=0; i<n; i++){ if(a[i]%2==1) { count1++; } dp[i] =count1; } int prev; long count=0; for(int i=0; i<n; i++) { prev= i==0 ? 0:dp[i-1]; for(int j=i; j<n; j++) { if((dp[j] - prev) == m){ count++; } if(dp[j] - prev > m){ break; } } } cout<<count; }
source share