Data Structures & AlgorithmsModerateProduct Company SDE · CP practice
Problem: What is the maximum sum of a contiguous subarray of exactly length 3 in [5, -2, 7, 1, 0, 4]?
Problem: What is the maximum sum of a contiguous subarray of exactly length 3 in [5, -2, 7, 1, 0, 4]?
a = [5, -2, 7, 1, 0, 4] print(max(sum(a[i:i + 3]) for i in range(len(a) - 2)))What is printed?
- A. 15
- B. 10
- C. 8
- D. 11
Correct answer: B. 10
The windows of size 3 sum to 10, 6, 8 and 5, so the best is 5, −2, 7 = 10. Kadane's maximum subarray of any length gives 15, a window of size 2 gives 7 + 1 = 8, and a window of size 4 gives 5 − 2 + 7 + 1 = 11.
More Coding Interview Problems questions
- Problem: How many subsets of {1, 2, ..., 10} contain no two consecutive integers? python from itertools import combinations print(sum(1…
- Problem: How many integers in [1, 1000] are perfect squares or perfect cubes? python print(sum(1 for x in range(1, 1001) if any(k k == x…
- Problem: Greedy graph colouring assigns colours in vertex order 0, 1, 2, 3, 4, 5, giving each vertex the smallest colour (starting at 0)…
- Problem: In the undirected graph with edges 0-1, 0-2, 1-2, 1-3, 2-3, 3-4, how many simple paths (no repeated vertex) go from vertex 0 to…
- Problem: An undirected forest (a graph with no cycles) has 9 vertices and 6 edges. How many connected components does it have?
- Problem: A rooted tree (root 1) has parent pointers: 2→1, 3→1, 4→2, 5→2, 6→4, 7→6, 8→3, 9→8. How many nodes lie on the path between node 7…