A new kind of cannon is being tested. The cannon shoots cannonballs in a fixed direction. Each cannonball flies horizontally until it hits the ground, and then it rests there. Cannonballs are shot from different heights, so they hit the ground at different points.
You are given two arrays, A and B, containing M and N integers respectively. Array A describes the landscape in the direction along which the cannon is shooting. Elements of array A represent the height of the ground, going from the cannon outwards. Array B contains levels from which consecutive cannonballs are shot.
Assume that a cannonball is shot at level H.
- Let I be the smallest index, such that 0 < I < M and A[I] ≥ H. The cannonball falls at position I − 1 and increases the ground level A[I−1] by 1.
- If there is no such I, and H > A[I] for all 0 ≤ I < M, then the cannonball flies beyond the horizon and has no effect on the result.
- If H ≤ A, then the cannonball ricochets away and has no effect on the result either.
Write a function:
function solution($A, $B);
that, given arrays A and B, simulates the flight of the cannonballs and returns the final contents of array A (denoted by A1) representing the final shape of the ground along the line of fire.
For example, given the following arrays A and B, of size M = 9 and N = 11 respectively:A = 1 A = 2 A = 0 A = 4 A = 3 A = 2 A = 1 A = 5 A = 7 B = 2 B = 8 B = 0 B = 7 B = 6 B = 5 B = 3 B = 4 B = 5 B = 6 B= 5
the function should return the following array A1 of M = 9 integers:A1 = 2 A1 = 2 A1 = 2 A1 = 4 A1 = 3 A1 = 3 A1 = 5 A1 = 6 A1 = 7
Write an efficient algorithm for the following assumptions:
- M and N are integers within the range [0..30,000];
- each element of arrays A, B is an integer within the range [0..1,000,000].
The following issues have been detected: timeout errors.
very small testcases
almost level line
small random test
small pyramid test
medium increasing array A
running time: >4.03 sec., time limit: 3.08 sec.
large increasing array A with some wells
running time: >5.01 sec., time limit: 4.72 sec.
big random constantly increasing array A
running time: >7.03 sec., time limit: 6.36 sec.
large increasing sequence with balls at same level
running time: >12.03 sec., time limit: 11.04 sec.
big increasing array A
running time: >11.05 sec., time limit: 10.40 sec.
big increasing array A with some wells
running time: >11.03 sec., time limit: 10.44 sec.