PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000118. Tìm chỉ số giữa cân bằng (Find the Middle Index in Array)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tìm chỉ số giữa cân bằng (Find the Middle Index in Array)

Find the Middle Index in Array

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

An array of nn integers a0,a1,…,an−1a_0,a_1,\ldots,a_{n-1} is indexed from 0. An index ii is balanced if the sum strictly to its left equals the sum strictly to its right. The element aia_i belongs to neither sum. An empty side has sum 0. Find the smallest balanced index, or return −1-1 if none exists.

Input

The first line contains integer nn.

The second line contains nn integers a0,…,an−1a_0,\ldots,a_{n-1}.

Output

Print one integer: the smallest balanced index (zero-based), or −1-1 if none exists.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le 20; −1000≤ai≤1000-1000\le a_i\le 1000; 0≤i<n0\le i<n.
  • Subtask 2 (30 points): 1≤n≤1001\le n\le 100; 1≤ai≤10001\le a_i\le 1000; 0≤i<n0\le i<n.
  • Subtask 3 (50 points): 1≤n≤1001\le n\le 100; −1000≤ai≤1000-1000\le a_i\le 1000; 0≤i<n0\le i<n.

Example 1

Input

5
2 3 -1 8 4

Output

3

Explanation

The left/right pairs at indices 0, 1, 2 are (0,14)(0,14), (2,11)(2,11), (5,12)(5,12). At index 3, the left sum 2+3−1=42+3-1=4 equals the right sum 4.

Example 2

Input

3
1 -1 4

Output

2

Explanation

At 0 the sums are 0 and 3; at 1 they are 1 and 4. At 2, the left sum is 1−1=01-1=0 and the empty right side also sums to 0.

Example 3

Input

2
2 5

Output

-1

Explanation

At 0 the sums are 0 and 5; at 1 they are 2 and 0. Neither index is balanced.