LeetCode-easy-Maximum Subarray (DP:Dynamic Programming)

Maximum Subarray

DP stands for the problem (Dynamic Programming)

https://www.freecodecamp.org/news/follow-these-steps-to-solve-any-dynamic-programming-interview-problem-cc98e508cd0e/
proposal directly reading this article, really good, though in English, but are all simple words, only a few technical terms, check on the line, do not recommend Google translate, because I looked at some places or your own understanding is better, Google translation error

The above documents for DP problem Detailed

Here are seven steps to solve the key problem of DP (given by the original Bowen)

  • How to recognize a DP problem
  • Identify problem variables
  • Clearly express the recurrence relation
  • Identify the base cases
  • Decide if you want to implement it iteratively or recursively
  • Add memoization
  • Determine time complexity

For the first step, how to identify whether a problem is the DP problem, we first go to determine whether the problems we face can be divided into sub-problems (see here many sub-problems it is natural to think of recursion, indeed original to say, but a simple recursive inefficient, need to use information already found a recursive quickly), like on this question, we find a sequence of the largest sub-sequence, and outputs the sum.
Then it can be seen, there is a null value, followed by the value to add into the array, and then stay relatively the largest, so continue to join one process, we can be regarded as one of the small child problem. (Formerly Bowen of the first step is seen as the most important step)
other steps, I think it is original to speak more clearly, not here incompetence.
Conclusion is that, to find the key variables from sub-problems, and then find reproduce the relationship between the main and sub-problems problem, and then decide whether you are using a non-recursive or recursive, the last memory is added to reproduce the data set (can be an array , may also be in other forms, anyway, to store information that you have found), then write.

Then the solution is to this question, in contrast, is easier to understand and follow this idea code.

class Solution {
public:
    int MaxSubarray(vector<int> &nums) {
        if (nums.size() == 0) return 0;
        if (nums.size() == 1)return nums.at(0);//前两步都是简单的检查,如果容器内没有元素或是只有一个那么就返回0或者是返回其本身
        int Memory_Max = nums.at(0);//记忆最大值
        int Real_Max = nums.at(0);//在当前步骤中的最大值,这也是子问题与主问题产生联系的地方
        size_t nums_length = nums.size();
        for (size_t i = 1; i != nums_length; i++) {
            Memory_Max = std::max(Memory_Max + nums.at(i), nums.at(i));//这一步就是将记忆的最大值与后面的值相加,再与其比较,也就是不断添加的过程,将当前的已加入的数据序列的最大序列的值记忆。
            //其实这个思想很想迪杰斯特拉寻找最短路径的问题(没学过数据结构的朋友可以把这里忽略)
            //不断把最短路径找出,并且在寻找过程中不断的更新最短路径的节点

            Real_Max = std::max(Memory_Max, Real_Max);//与当前真实最大值进行比较
        }
        return Real_Max;

    }
};

Guess you like

Origin www.cnblogs.com/Yekko/p/12150320.html