Perfect Subarray

3.7

28 votes
Arrays, Data Structures, Easy, One-dimensional, Prefix sum, prefix-sum
Problem

You are given an array A of N integers. You need to count the subarrays which have the sum of all elements in it a perfect square.

Input
The first line contains an integer N that denotes count of elements in the array. Next line contains N space separated integers that denote elements of the array.

Output
In the output, you need to print the count of subarrays for which the sum of elements is a perfect square.

Constraints
1N5000
1A[i]106

Sample Input
4
1 4 2 3
Sample Output
3
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The given array is: 1 4 2 3

Let us list the sum of all possible subarrays:

[1 , 1] = 1
[1 , 2] = 1 + 4 = 5
[1 , 3] = 1 + 4 + 2 = 7
[1 , 4] = 1 + 4 + 2 + 3 = 10
[2 , 2] = 4
[2 , 3] = 4 + 2 = 6
[2 , 4] = 4 + 2 + 3 = 9
[3 , 3] = 2
[3 , 4] = 2 + 3 = 5
[4 , 4] = 3

[1, 4, 9] = 3

Editor Image

?