LeetCode happy brush title twenty-eight days --53. Maximum Subarray

Nowadays,My life is a little chaotic.The progress of problem solving has slowed down. I hope I can actively adjust my state in the future and complete the tasks that should be completed every day

53. Maximum Subarray
Easy

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

This probem is easy and belong to dynamic program.But after I hear the class talk about DP  I still can't figure out the answer.

At my present stage, only by making more contact with problems can I finally develop the ability to solve problems by myself. Therefore, the battle formation should be "quick and quick" rather than "protracted".

BONUS:
1.vector initialise with size of space

 

vector<int> f(nums.size());

 

2.vector max value can call function,remember to add * before max_element,the type of value is different

 

*max_element(f.begin(),f.end())

 

FULL CODE C++:

#include<stdio.h>
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
using namespace std;
// Author: Huahua
// Runtime: 3 ms
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        vector<int> f(nums.size());
        f[0]=nums[0];
        for(int i=1;i<nums.size();i++)
        {
            f[i]=max(f[i-1]+nums[i],nums[i]);
        }
        return *max_element(f.begin(),f.end());

    }
};

int main()
{
    Solution s;
    vector<int> nums={-2,1,-3,4,-1,2,1,-5,4};
    int res=s.maxSubArray(nums);
    cout<<res<<endl;
    return 0;
}

Python version:

arr=input("")
nums=[int(n) for n in arr.split(",")]
print(nums)
#nums=[-2,1,-3,4,-1,2,1,-5,4]

All python input is string,so directly input and deal with it.Use "," to  split the input array.if the array is divided by space don't need write anything.Nums can be assign value by for loop.

FULL CODE PYTHON VERSION:

ATTENTION:the minimum value set should use -2147483647,this is the min value of int

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        #local->l,global->g
        l=g=-2147483647
        for i in nums:
            l=max(i,l+i)
            g=max(g,l)
        return g


solu=Solution()
arr=input("")
nums=[int(n) for n in arr.split(",")]
print(nums)
#nums=[-2,1,-3,4,-1,2,1,-5,4]
print(solu.maxSubArray(nums))

Theroy:

the variable l means local,g means global,each variable in nums compare the sum of the above & current element the bigger one is local max,and compare local max&global max,the bigger one to be the global max.

Guess you like

Origin www.cnblogs.com/Marigolci/p/11306535.html