Data Structure & Algorithms
  • 🖌️Unlocking the Power of Algorithms with C#
  • Data Structure
    • Data Structure
    • Big O
    • Array
    • Linked Lists
    • Stacks
    • Queues
    • Hash Tables
    • Trees
    • Graphs
    • Heap Sort
    • ParkingLot Algorithm
    • LRU cache
    • Priority Queue
  • Algorithms
    • Algorithm
    • Recursion
    • Sorting
    • Searching
    • Dynamic Programming
  • Problems
    • Array
      • Two Sum
      • Two Sum II - Input Array Is Sorted
      • Contains Duplicate
      • Maximum Subarray
      • House Robber
      • Move Zeroes
      • Rotate Array
      • Plus One
      • Find number of subarrays with even length
      • Find number of subarrays with even sum
      • Find Missing Element
      • Reduce Array Size to The Half
      • Remove Duplicates
      • Merge Sorted Arrays
      • Arrays Intersection
      • 3Sum
      • Trapping Rain Water
      • Maximum sum of a subarray
      • Longest Subarray
      • Subarray Sum Equals K
      • Container With Most Water
      • Missing Number
      • Roman to Integer
      • First Missing Positive
      • Unique Integers That Sum Up To 0
      • Integer to Roman
      • Flatten
    • String
      • Check if two strings are permutation of each other
      • String Compression
      • Palindrome Permutation
      • Determine if a string has all Unique Characters
      • One Away
      • Longest Substring Without Repeating Characters
      • Valid Palindrome
      • Valid Palindrome II
      • Backspace String Compare
      • First Unique Character in a String
      • Is Subsequence
      • URLify a given string
      • String has same characters at same position
      • Number of Ways to Split a String
      • Check whether two Strings are anagram of each other
      • Print last `n` lines of a big file or big string.
      • Multiply Strings
    • Matrix
      • Search a 2D Matrix
      • Search a 2D Matrix II
      • Rotate Matrix
      • Spiral Matrix
      • Set Matrix Zeroes
    • Bit Manipulation
      • Sum of Two Integers
      • Reverse Number
      • Reverse Number II
      • Binary Bits Count
      • Binary Bits Count II
    • Stack
      • Valid Parentheses
      • Balance or not expression
      • Decode String
    • Tree
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Return All Root-To-Leaf Paths
      • Binary Tree Height-Balanced
      • Valid Binary Search Tree
      • Binary Tree Sum of all left leaves.
    • Linked List
      • Linked List Delete Middle Node
      • Merge Sorted Linked List
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Unsorted List
      • Linked List Cycle
    • Graph
      • The Number Of Islands
      • Number of Closed Islands
      • Max Area of Island
      • Rotting Oranges
      • Number of Provinces
      • Course Schedule
      • Surrounded Regions
      • Snakes and Ladders
      • Widest Path Without Trees
      • Knight Probability in Chessboard
      • Possible moves of knight
      • Check Knight Tour Configuration
      • Steps by Knight
      • Network Delay Time
    • Greedy
      • Best Time to Buy and Sell Stock
      • Best Time to Buy and Sell Stock II
      • Smallest Subset Array
      • Jump Game
    • Backtracking
      • Towers of Hanoi
      • Subsets
      • Combination Sum
      • Sudoku Solver
      • Word Search
    • Heap
      • Kth Largest Element in an Array
      • Top K Frequent Elements
    • Sorting
      • Order Colors String
    • Recursion
      • Number To Text
      • Divide Number
Powered by GitBook
On this page
  1. Problems
  2. Array

Maximum Subarray

Array, Dynamic Programming

Given an integer array nums, find the subarray with the largest sum, and return its sum. Here, array can contains duplicate or nagative numbers also.

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.

Solutions

Calculates the maximum sum ending at each position and ensures that this sum is the maximum seen so far.

Approach – Brute Force Technique

This algorithm works by calculating the sum of every possible subarray in the input array and updating maxSum whenever a larger sum is found.

Steps

  1. Initialize: Set maxSum to the smallest possible integer. This variable will keep track of the maximum subarray sum we've encountered so far.

  2. Iterate through the array: For each element in the array (index i from 0 to nums.Length - 1), calculate the sum of all subarrays starting at this position. This is done by another loop (index j from i to nums.Length - 1) that adds the current element (nums[j]) to sum.

  3. Update maxSum: If sum is greater than maxSum, update maxSum with the value of sum. This step keeps track of the maximum sum of any subarray seen so far.

  4. Return the result: After going through all the elements of the array and all possible subarrays, return maxSum which now contains the maximum sum of a subarray in the array.

public class Solution {
    public int MaxSubArray(int[] nums) {
        int maxSum = Int32.MinValue;
        for (int i = 0; i < nums.Length; i++) {
            int sum = 0;
            for (int j = i; j < nums.Length; j++) {
                sum += nums[j];
                maxSum = Math.Max(maxSum, sum);
            }
        }
        return maxSum;
    }
}

Complexity

  • Time Complexity: O(n^2)

  • Auxiliary Space: O(1)

Approach – Dynamic Programming Technique

It calculates the maximum sum ending at each position and ensures that this sum is the maximum seen so far. If the sum becomes less than the current element, it means the sum of the previous subarray is negative and thus not worth keeping, so it starts a new subarray from the current position.

Steps

  1. Initialize: Set maxCurrent and maxGlobal to the first element of the array. These variables will keep track of the maximum subarray sum we've encountered so far (maxGlobal) and the maximum sum ending at the current position (maxCurrent).

  2. Iterate through the array: For each element from the second to the last (index i from 1 to nums.Length - 1), update maxCurrent to be the maximum of the current element (nums[i]) and the sum of the current element and the previous maxCurrent (maxCurrent + nums[i]). This step essentially says, "consider the current element as the start of a new subarray or include it in the sum of the existing subarray."

  3. Update maxGlobal: If maxCurrent is greater than maxGlobal, update maxGlobal with the value of maxCurrent. This step keeps track of the maximum sum of any subarray seen so far.

  4. Return the result: After going through all the elements of the array, return maxGlobal which now contains the maximum sum of a subarray in the array.

public class Solution
{
    public int MaxSubArray(int[] nums)
    {
        int maxCurrent = nums[0];
        int maxGlobal = nums[0];

        for (int i = 1; i < nums.Length; i++)
        {
            maxCurrent = Math.Max(nums[i], maxCurrent + nums[i]);
            if (maxCurrent > maxGlobal)
            {
                maxGlobal = maxCurrent;
            }
        }
        return maxGlobal;
    }
}

Complexity

  • Time Complexity: O(n)

  • Auxiliary Space: O(1)

PreviousContains DuplicateNextHouse Robber

Last updated 1 year ago