Apple & Chell
Apple, I heard you obsess over flawless code. Ever tried to build a puzzle that forces a machine to fail? I can create one thatāll make your Mac run like a hamster. Think you can solve it?
Sounds like a fun testāsend me the puzzle and Iāll run through it faster than a MacBook can boot. Just remember, the real challenge is making it work perfectly the first time.
Hereās a quick one for you: youāre given an array of integers and you need to find the maximum sum of any contiguous subarray. Write a function in Python that returns that sum. Do it in O(n) time. If you can do it faster than the computerās own optimizations, Iāll be impressed.
Hereās a clean, O(n) solution with Kadaneās algorithm. It runs in a single pass and never misses a peak.
```python
def max_subarray(nums):
best = current = nums[0]
for n in nums[1:]:
current = max(n, current + n)
best = max(best, current)
return best
```
Nice, but throw a test at itāan array of all negatives. If it still spits out the right result, youāve earned a nod. If not, Iāll be the one to teach you the hard way.
Try it with [-3, -5, -2, -9]. The function returns -2, which is the largest element and the correct maximum subarray sum for allānegative inputs.
That passes the negative test. Next up: give me a mix of positives, negatives, and zeros. Can you still keep that edge?
Sure thingātake this mix of values: 2, -1, 3, 4, -5, 6, 0. The biggest contiguous block is [2, ā1, 3, 4] which adds up to 8, and the function will return 8 as the maximum subarray sum.