LeetCode: Maximum Subarray

From Leetcode, a classic interview problem: https://leetcode.com/problems/maximum-subarray/:

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
There are ways to do it in O(n)-time and O(1)-space. The method that is shown here is an O(n)-time, O(n)-space, but it exemplifies the usage of extra memory to minimize the execution time of an algorithm.
The storage auxiliary memory will store the max value of the subarray ending at position i. With that information, all it needs to be done at position i+1 is look at the max array at position i and decide whether it is better to add that element or not. Faster than 87% of the c# submissions. Cheers, Marcelo.
    public class Solution
    {
        public int MaxSubArray(int[] nums)
        {
            if (nums == null || nums.Length == 0) return 0;

            long[] max = new long[nums.Length];

            max[0] = nums[0];
            long maxRetVal = max[0];

            for (int i = 1; i < nums.Length; i++)
            {
                max[i] = nums[i];
                if (max[i - 1] + nums[i] > max[i])
                {
                    max[i] = max[i - 1] + nums[i];
                }
                if (max[i] > maxRetVal)
                {
                    maxRetVal = max[i];
                }
            }

            return (int)maxRetVal;
        }
    }

Comments

  1. I was asked this question on my interview with Bing at Moscow :)
    The fact that you're using only max[i] and max[i-1] suggests that there is no real need to keep an array of previous values - one suffices. Basic idea is following - we maintain the running sum, which at every iteration is used to potentially update the total max, and discard it when it becomes negative, since it's strictly easier to get to positive number from 0 than from some negative number.

    class Solution {
    public:
    int maxSubArray(const vector& nums) {
    int max_so_far = nums.front();
    int running_sum = 0;
    for (int num : nums) {
    running_sum += num;
    max_so_far = max(max_so_far, running_sum);
    running_sum = max(0, running_sum);
    }
    return max_so_far;
    }
    };

    So many sweet memories :) Thanks!

    ReplyDelete

Post a Comment

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

Hard Leetcode Problem: Grid Illumination