Problem Link - Maximum Subarray Sum in Arrays
Problem Statement:
Given an integer array nums, find the subarray with the largest sum, and print its sum.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
Approach:
We will check for every possible subarray:
- Iterate over all possible starting indices of the subarray.
- For each starting index, iterate over all possible ending indices (greater than or equal to the starting index).
- Calculate the sum of elements between the starting and ending index (inclusive).
- Keep track of the maximum sum encountered during this process.
Complexity:
-
Time Complexity:
O(N^3)
For each testcase there are(N*(N+1))/2
. subarrays. This will result inO(N^2)
time complexity. For each subarray, calculating the sum takesO(N)
in the worst case. -
Space Complexity:
O(1)
No extra space used.