[LeetCode] 14.Maximum Subarray
2021. 1. 18. 16:30
leetcode.com/problems/maximum-subarray/
1. Problem
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
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 = [-100000] Output: -100000
Constraints:
- 1 <= nums.length <= 3 * 104
- -105 <= nums[i] <= 105
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.
2. Code
package leetCode;
public class MaximumSubarray {
public static void main(String[] args) {
int[] input = {-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubArray(input));
}
public static int maxSubArray(int[] nums) {
int maxSum = nums[0];
for(int i = 0; i < nums.length; i++) {
int maxTemp = nums[i];
int temp = 0;
for(int j = i; j < nums.length; j++) {
temp = temp + nums[j];
if(maxTemp <= temp) {
maxTemp = temp;
}
}
if(maxSum <= maxTemp) {
maxSum = maxTemp;
}
}
return maxSum;
}
}
3. Report
굉장히 시간이 낮게 나왔다
너무 노가다했나..?
'Algorithm > 문제' 카테고리의 다른 글
[LeetCode] 16.3Sum (0) | 2021.01.21 |
---|---|
[LeetCode] 15.Insert Interval (again) (0) | 2021.01.18 |
[LeetCode] 13.Plus One (0) | 2021.01.17 |
[LeetCode] 12.Length of Last Word (0) | 2021.01.14 |
[LeetCode] 11.Implement strStr() (0) | 2021.01.08 |