1. What is Dynamic Programming?
Dynamic Programming (DP) is an algorithm design technique that solves complex problems by breaking them down into smaller subproblems and storing the results of already computed values to avoid redundant calculations. It is mainly used for optimization problems, reducing time complexity and providing efficient solutions.
1.1. Characteristics of Dynamic Programming
- Optimal Substructure: The optimal solution to the problem must include optimal solutions to its subproblems.
- Overlapping Subproblems: Prevents the same subproblem from being solved multiple times.
2. Problem Introduction
Problem: Maximum Subarray Sum
This problem involves finding the maximum sum of a contiguous subarray within an array of integers. For example, the maximum subarray sum of the array {-2, 1, -3, 4, -1, 2, 1, -5, 4}
is 6
, which is the sum of the subarray {4, -1, 2, 1}
.
Input
- The first line contains the size of the array
N
(1 ≤ N ≤ 100,000). - The second line contains the elements of the array separated by spaces.
Output
Print the maximum subarray sum.
3. Problem Solving Process
3.1. Approach
To solve this problem using dynamic programming, the following steps can be taken:
- Define the problem: Define
dp[i]
as the maximum subarray sum up to thei
th element. - Establish the recurrence relation: The recurrence relation is
dp[i] = max(arr[i], dp[i-1] + arr[i])
. That is, decide whether to include thei
th element or not. - Set initial values: Start with
dp[0] = arr[0]
. - Calculate the maximum: Iterate through all elements to update the maximum value.
3.2. C++ Code Implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int N;
cin >> N;
vector arr(N);
for(int i = 0; i < N; i++) {
cin >> arr[i];
}
vector dp(N);
dp[0] = arr[0];
int maxSum = dp[0];
for(int i = 1; i < N; i++) {
dp[i] = max(arr[i], dp[i - 1] + arr[i]);
maxSum = max(maxSum, dp[i]);
}
cout << maxSum << endl;
return 0;
}
4. Code Explanation
The above code first takes the size of the array N
and the elements of the array as input. Then, it declares a dp
array to store the maximum subarray sum up to each index. After that, it updates the dp
values inside a loop while finding the maximum value in the process.
4.1. Time Complexity
The time complexity of this algorithm is O(N)
. It has linear time complexity because it iterates through the array once.
4.2. Space Complexity
The space complexity is also O(N)
, as it stores up to N
values. However, there is a method to find the maximum sum using just two variables without using the dp
array.
5. Conclusion
Dynamic programming is a powerful technique for efficiently solving complex problems. The maximum subarray sum problem helps understand the basic concepts of dynamic programming and often appears in coding tests, making sufficient practice necessary.