This question requires an O(n) algorithm. After querying, it is found that dynamic programming algorithms, greedy algorithms and divide-and-conquer methods can be solved.
Here I use dynamic programming to solve this problem.
Introduce:
In a multi-stage decision-making problem, the decisions taken at each stage are generally time-related. The decision-making depends on the current state and immediately causes the transfer of the state. A decision sequence is generated in the changing state, so there is The meaning of "dynamic" refers to the process of solving multi-stage decision-making optimization as a dynamic programming method.
Basic idea:
Dynamic programming algorithms are often used to solve problems with some optimal properties. In this type of problem, there may be many feasible solutions. Each solution corresponds to a value, and we want to find the solution with the optimal value. The dynamic programming algorithm is similar to the divide and conquer method . Its basic idea is to decompose the problem to be solved into several sub-problems, first solve the sub-problems, and then obtain the solution of the original problem from the solutions of these sub-problems. Different from the divide and conquer method, it is suitable for the problem solved by dynamic programming, and the sub-problems obtained through decomposition are often not independent of each other. If the divide-and-conquer method is used to solve such problems, the number of sub-problems obtained by decomposition is too large, and some sub-problems are repeatedly calculated many times. If we can save the answers to the sub-problems that have been solved, and find out the answers that have been obtained when needed, we can avoid a lot of repeated calculations and save time. We can use a table to record the answers to all solved subproblems. Regardless of whether the sub-problem is used in the future, as long as it has been calculated, its result will be filled in the table. This is the basic idea of dynamic programming method. There are various specific dynamic programming algorithms, but they all have the same form of filling the table.
Code below:
class Solution {
public int maxSubArray(int[] nums) {
//dynamic programming
int max=nums[0];
int res=0;
int n=nums.length;
if(n==1)return nums[0];
for(int i:nums){
//foreach statement
res = Math.max(res+i,i);
//Judge whether the sum of the previous numbers is positive, otherwise start from scratch
max=Math.max(max,res);
//Store the previous value and find the maximum value with res
}
return max;
}
}