하루의 쉼터

[LeetCode] 53. Maximum Subarray 본문

Coding Test/LeetCode

[LeetCode] 53. Maximum Subarray

Changun An 2020. 11. 30. 23:18
반응형

Question :

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

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.

 

Example 1:

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

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [0]
Output: 0

Example 4:

Input: nums = [-1]
Output: -1

Example 5:

Input: nums = [-2147483647]
Output: -2147483647

 

Constraints:

 1<=nums.length <=2*104

-231 <=nums[i]<=231-1

Solution.h

#include<iostream>
#include<vector>
#include<algorithm>
#include <limits>
class Solution
{
public:
    int maxSubArray(std::vector<int>& nums);

};

 

Solution.cpp

#include "Solution.h"

int Solution::maxSubArray(std::vector<int>& nums)
{
	int result = nums[0];
	int temp = nums[0];

	for (int i = 1; i < nums.size(); i++) {
		temp = std::max(nums[i], temp + nums[i]);
		result = std::max(temp, result);
	}
	return result;
}

 

Result :
Runtime: 12 ms, faster than 66.98% of C++ online submissions for Maximum Subarray.
Memory Usage: 13.5 MB, less than 59.66% of C++ online submissions for Maximum Subarray.

 

Github : github.com/Anchangun/LeetCode

 

Anchangun/LeetCode

문제풀이. Contribute to Anchangun/LeetCode development by creating an account on GitHub.

github.com

 

반응형

'Coding Test > LeetCode' 카테고리의 다른 글

[LeetCode] 7. Reverse Integer  (0) 2021.10.05
[LeetCode] 206. Reverse Linked List  (0) 2020.12.06
[LeetCode] 21. Merge Two Sorted Lists  (0) 2020.11.24
[LeetCode] 136. Single Number  (0) 2020.11.23
[LeetCode] 20. Valid Parentheses  (0) 2020.11.17
Comments