Skip to main content
added 613 characters in body
Source Link
Janne Karila
  • 10.4k
  • 20
  • 34

This program computes sums over a sliding window of fixed size, and takes the maximal sum. This is not Kadane's algorithm, which solves the more difficult problem where the size of the subarray is not predefined.

To improve performance, you should take better advantage of NumPy. Avoid Python loops by vectorized operations. Using numpy.cumsum over the full 2D array would be a good starting point.


Here's how you could vectorize kadane1DwithBounds. I changed naming as well. From the cumulative sums you can get the sliding sums by subtracting at an offset. The advantage over your version is that the Python for loop is replaced by array operations that are implemented in C. If you are not familiar with the concept, I suggest reading the What is NumPy? page.

def max_sliding_sum(array, window_size):
    cum_sum = np.cumsum(array)
    sliding_sum = cum_sum[window_size:] - cum_sum[:-window_size]
    return sliding_sum.max()

This program computes sums over a sliding window of fixed size, and takes the maximal sum. This is not Kadane's algorithm, which solves the more difficult problem where the size of the subarray is not predefined.

To improve performance, you should take better advantage of NumPy. Avoid Python loops by vectorized operations. Using numpy.cumsum over the full 2D array would be a good starting point.

This program computes sums over a sliding window of fixed size, and takes the maximal sum. This is not Kadane's algorithm, which solves the more difficult problem where the size of the subarray is not predefined.

To improve performance, you should take better advantage of NumPy. Avoid Python loops by vectorized operations. Using numpy.cumsum over the full 2D array would be a good starting point.


Here's how you could vectorize kadane1DwithBounds. I changed naming as well. From the cumulative sums you can get the sliding sums by subtracting at an offset. The advantage over your version is that the Python for loop is replaced by array operations that are implemented in C. If you are not familiar with the concept, I suggest reading the What is NumPy? page.

def max_sliding_sum(array, window_size):
    cum_sum = np.cumsum(array)
    sliding_sum = cum_sum[window_size:] - cum_sum[:-window_size]
    return sliding_sum.max()
Source Link
Janne Karila
  • 10.4k
  • 20
  • 34

This program computes sums over a sliding window of fixed size, and takes the maximal sum. This is not Kadane's algorithm, which solves the more difficult problem where the size of the subarray is not predefined.

To improve performance, you should take better advantage of NumPy. Avoid Python loops by vectorized operations. Using numpy.cumsum over the full 2D array would be a good starting point.