0% found this document useful (0 votes)
10 views18 pages

Array 03

The document presents three algorithmic problems related to arrays: Maximum Subarray Sum, Maximum Consecutive Ones, and Maximum Difference Between Increasing Elements. Each problem includes a detailed problem statement, example inputs and outputs, and multiple solutions with varying time and space complexities. The document also provides links to the corresponding LeetCode problems for further reference.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

Array 03

The document presents three algorithmic problems related to arrays: Maximum Subarray Sum, Maximum Consecutive Ones, and Maximum Difference Between Increasing Elements. Each problem includes a detailed problem statement, example inputs and outputs, and multiple solutions with varying time and space complexities. The document also provides links to the corresponding LeetCode problems for further reference.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

ARRAY PROBLEM - 03

13 February 2024 21:19

01 - MAXIMUM SUB-ARRAY SUM

02 - MAXIMUM CONSECUTIVE ONE'S

03 - MAXIMUM DIFFERENCE BETWEEN


INCREASING ELEMENT

CREATED BY - SHIVAM BAREKAR


MAXIMUM SUB-ARRAY SUM
15 February 2024 10:36

Problem Statement : Given an integer array nums, Find the


Subarray with the largest sum, and return its sum. ( Leetcode - 53 )

Link : https://leetcode.com/problems/maximum-subarray/description/

Example 1 :

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]


Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2 :

Input: nums = [1]


Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]


Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints :

1 <= nums.length <= 105


-104 <= nums[i] <= 104

Solution-01 : Brute-Force Approach

Intuition :

We will check the sum of every possible subarray and consider the maximum
among them. To get every possible subarray sum, we will be using three
nested loops. The first loops(say i and j) will iterate over every possible
starting index and ending index of a subarray. Basically, in each iteration,
the subarray range will be from index i to index j. Using another loop we will
get the sum of the elements of the subarray [i…..j]. Among all values of the
sum calculated, we will consider the maximum one.

Approach :

The steps are as follows :

• First, we will run a loop(say i) that will select every possible starting
index of the subarray. The possible starting indices can vary from
index 0 to index n-1(n = size of the array).
• Inside the loop, we will run another loop(say j) that will signify the
ending index of the subarray. For every subarray starting from the
index i, the possible ending index can vary from index i to n-1(n = size
of the array).
• After that for each subarray starting from index i and ending at index
j (i.e. arr[i….j]), we will run another loop to calculate the sum of all the
elements(of that particular subarray).

Note : We are selecting every possible subarray using two nested loops and
for each of them, we add all its elements using another loop.

Dry Run :

Subarrays are marked with yellow color.


Output : The maximum subarray sum is: 6

Complexity Analysis :

Time Complexity: O(N3), where N = size of the array.


Reason: We are using three nested loops, each running approximately N
times.

Space Complexity: O(1) as we are not using any extra space.

Solution-02 : Better Approach

Intuition :

If we carefully observe, we can notice that to get the sum of the current
subarray we just need to add the current element(i.e. arr[j]) to the sum of
the previous subarray i.e. arr[i….j-1].
Assume previous subarray = arr[i……j-1]
current subarray = arr[i…..j]
Sum of arr[i….j] = (sum of arr[i….j-1]) + arr[j]
This is how we can remove the third loop and while moving j pointer, we can
calculate the sum.
Approach :

The steps are as follows :

• First, we will run a loop(say i) that will select every possible starting
index of the subarray. The possible starting indices can vary from
index 0 to index n-1(n = array size).
• Inside the loop, we will run another loop(say j) that will signify the
ending index as well as the current element of the subarray. For every
subarray starting from index i, the possible ending index can vary from
index i to n-1(n = size of the array).
• Inside loop j, we will add the current element to the sum of the
previous subarray i.e. sum = sum + arr[j]. Among all the sums the
maximum one will be the answer.

Dry Run :

Subarrays are marked with yellow color.


Output : The maximum subarray sum is: 6

Complexity Analysis :

Time Complexity: O(N2), where N = size of the array.


Reason: We are using two nested loops, each running approximately N
times.

Space Complexity: O(1) as we are not using any extra space.

Solution-03 : Optimal Approach

Intuition :

The intuition of the algorithm is not to consider the subarray as a part of


the answer if its sum is less than 0. A subarray with a sum less than 0 will
always reduce our answer and so this type of subarray cannot be a part of
the subarray with maximum sum.

Here, we will iterate the given array with a single loop and while iterating we
will add the elements in a sum variable. Now, if at any point the sum
becomes less than 0, we will set the sum as 0 as we are not going to consider
any subarray with a negative sum. Among all the sums calculated, we will
consider the maximum one.
Thus we can solve this problem with a single loop.

Approach :

The steps are as follows :

• We will run a loop(say i) to iterate the given array.


• Now, while iterating we will add the elements to the sum variable and
consider the maximum one.
• If at any point the sum becomes negative we will set the sum to 0 as
we are not going to consider it as a part of our answer.

Note: In some cases, the question might say to consider the sum of the
empty subarray while solving this problem. So, in these cases, before
returning the answer we will compare the maximum subarray sum calculated
with 0(i.e. The sum of an empty subarray is 0). And after that, we will
return the maximum one.

For e.g. if the given array is {-1, -4, -5}, the answer will be 0 instead of -1 in
this case.

This is applicable to all the approaches discussed above.

But if this case is not explicitly mentioned we will not consider this case.
Output : The maximum subarray sum is: 6

Complexity Analysis :

Time Complexity: O(N), where N = size of the array.


Reason: We are using a single loop running N times.

Space Complexity: O(1) as we are not using any extra space.

Submission on Leetcode :
MAXIMUM CONSECUTIVE ONE'S
15 February 2024 11:11

Problem Statement : Given a binary array nums and an integer k,


return the maximum number of consecutive 1's in the array if you can
flip at most k 0's. ( Leetcode - 1004 )

Link : https://leetcode.com/problems/max-consecutive-ones-
iii/description/

Example 1 :

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2


Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1] Bolded numbers were flipped from 0 to 1.
The longest subarray is underlined.

Example 2 :

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3


Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] Bolded numbers were flipped
from 0 to 1. The longest subarray is underlined.

Constraints :

1 <= nums.length <= 105


nums[i] is either 0 or 1.
0 <= k <= nums.length

Solution :

Optimal Approach :

We are dealing with “sliding window” approach

Constraints :

k zeros flip (means how much we have given ‘k’ values then we can flip that
zeros to get consecutive maximum 1's)
We get subarrays

Window size : ( j-i+1 )

Algorithm :

• First initialize two pointers both will start from beginning. These
pointers basically represent left and right boundary of sliding window.
• Then increment the right pointer ‘j’ unless it will be equal to ‘k’. This
ensures the number of zeros in sliding window is not greater than ‘k’.
• If the size of zeros exceeds then we stop ‘j’ and then moves ‘i’ to
shrink the window until it met the condition again.
• At each step we will update our initialized variable ‘ans’ that will keep
track of number of one’s.

Complexity Analysis :

Time Complexity :The time complexity of given problem is O(N), N is length


of binary array ‘nums’. In worst case scenario both pointers are visiting
entire elements only once.

Space Complexity : The space complexity is O(1), because there is no extra


space is needed. And the additional initialized variables (i, j, ans, zeroCount)
have fixed amount of memory instead of input size.
Submission on Leetcode :
MAXIMUM DIFFERENCE BETWEEN INCREASING
ELEMENT
15 February 2024 11:40

Problem Statement : Given a 0-indexed integer array nums of


size n, find the maximum difference between nums[i] and nums[j]
(i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] <
nums[j].
Return the maximum difference. If no such i and j exists, return
-1. ( Leetcode - 2016 )

Link : https://leetcode.com/problems/maximum-difference-
between-increasing-elements/description/

Example 1 :

Input: nums = [7,1,5,4]


Output: 4
Explanation :
The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i]
= 5 - 1 = 4.
Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1
= 6, but i > j, so it is not valid.

Example 2 :

Input: nums = [9,4,3,2]


Output: -1
Explanation:
There is no i and j such that i < j and nums[i] < nums[j].

Example 3:

Input: nums = [1,5,2,10]


Output: 9
Explanation :
The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i]
= 10 - 1 = 9.

Constraints :

n == nums.length
2 <= n <= 1000
1 <= nums[i] <= 109

Solution-01 : Naive Approach :


We can solve this problem using two loops. In the outer loop, pick
elements one by one and in the inner loop calculate the difference of
the picked element with every other element in the array and
compare the difference with the maximum difference calculated so
far.

Below is the implementation of the above approach :


Output :

Maximum difference is 109

Complexity Analysis :

Time Complexity : O(n2)


Auxiliary Space : O(1)

Solution-02 : Efficient Approach :

In this method, instead of taking difference of the picked element


with every other element, we take the difference with the minimum
element found so far. So we need to keep track of 2 things :
1) Maximum difference found so far (max_diff).
2) Minimum number visited so far (min_element).

Below is the implementation of the above idea :


Output :

Maximum difference is 109

Complexity Analysis :

Time Complexity : O(n)


Auxiliary Space : O(1)

Solution-03 : Approach Using Kadane’s Algorithm :

First find the difference between the adjacent elements of the array
and store all differences in an auxiliary array diff[] of size n-1. Now
this problems turns into finding the maximum sum subarray of this
difference array. Thanks to Shubham Mittal for suggesting this
solution.
Output :

Maximum difference is 98
Complexity Analysis :

Time Complexity : O(n)


Auxiliary Space : O(1)

Submission on Leetcode :

You might also like