Problems/Dynamic Programming/Maximum Subarray Sum
Dynamic Programming
medium

Maximum Subarray Sum

The Maximum Profit Slice problem asks you to find the contiguous subarray within a given array of stock prices that yields the highest profit. This problem is a classic example of dynamic programming and tests your ability to optimize for time complexity.

arraydynamic programmingmaximum subarraykadane's algorithmoptimization

Problem Statement

Given an array of integers representing the daily price of a particular stock, find the contiguous subarray (containing at least one number) which has the largest sum. The sum represents the maximum profit you could have made by buying and selling the stock within that subarray.

Example 1
Input: [7, 1, 5, 3, 6, 4]
Output: 7
The subarray [1, 5, 3, 6] gives the maximum profit. Buying at 1 and selling at 6 results in a profit of 5. However, the subarray [1, 5, 3, 6, 4] gives a better result. The optimal subarray is [1, 5, 3, 6, 4] since 6-1 = 5, 5-1 = 4, 3-1 = 2, 6-1 = 5, 4-1 = 3. The maximum profit is 5.
Example 2
Input: [7, 6, 4, 3, 1]
Output: 0
In this scenario, the stock price is continuously decreasing. Therefore, no profit can be made. The maximum profit is 0, achieved by not buying or selling the stock at all.
Constraints
  • -The input array will contain at least one integer.
  • -The integers in the array can be positive, negative, or zero.
  • -The input array represents the daily stock prices.
  • -The goal is to find a contiguous subarray that maximizes profit.
  • -The array length will not exceed 10^5.

Brute Force Approach

The brute force approach would be like trying every possible combination of buy and sell dates. You calculate the profit for every possible subarray and keep track of the maximum profit found. This is like checking every possible route on a map to find the shortest, even if it means going down dead ends.

TimeO(n^2)
SpaceO(1)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem