Question 16
Back to Exercise
What is the output of the following Java program?
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {3, 1, 4, 1, 5, 9, 2};
int[] pre = new int[a.length + 1];
for (int i = 0; i < a.length; i++) pre[i + 1] = pre[i] + a[i];
System.out.println(Arrays.toString(pre));
System.out.println((pre[5] - pre[2]) + " " + (pre[7] - pre[0])); // sum of a[2..4] and of everything
}
}
- A [0, 3, 4, 8, 9, 14, 23, 25] 10 25 Correct
- B [3, 4, 8, 9, 14, 23, 25] 10 25
- C [0, 3, 4, 8, 9, 14, 23, 25] 9 25
- D [0, 3, 4, 8, 9, 14, 23, 25] 10 23
Correct Answer: Option A
pre[i] is the sum of the first i elements, so the sum of a[l..r] is pre[r + 1] - pre[l]: 4 + 1 + 5 = 10.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!