#PS0000118. Tìm chỉ số giữa cân bằng (Find the Middle Index in Array)
Bài tập thuộc lộ trình
Mục lục đề ⌄
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 integers is indexed from 0. An index is balanced if the sum strictly to its left equals the sum strictly to its right. The element belongs to neither sum. An empty side has sum 0. Find the smallest balanced index, or return if none exists.
Input
The first line contains integer .
The second line contains integers .
Output
Print one integer: the smallest balanced index (zero-based), or if none exists.
Subtasks
- Subtask 1 (20 points): ; ; .
- Subtask 2 (30 points): ; ; .
- Subtask 3 (50 points): ; ; .
Example 1
Input
5
2 3 -1 8 4
Output
3
Explanation
The left/right pairs at indices 0, 1, 2 are , , . At index 3, the left sum 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 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.