LeetCode_53. Maximum Subarray
2024-09-01 13:34:02
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.
package leetcode.easy; public class MaximumSubarray {
@org.junit.Test
public void test() {
int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
System.out.println(maxSubArray(nums));
} public int maxSubArray(int[] nums) {
int max = nums[0];
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
count = nums[i];
for (int j = i + 1; j < nums.length; j++) {
count += nums[j];
if (count > max) {
max = count;
}
}
}
return max;
}
}
最新文章
- js三种方法添加image
- diff 比较两个文件的差异
- Strcmp(字符串1,字符串2)函数 Sizeof &;&; strlen() Substr(a,b)
- 转载 jquery $(document).ready() 与window.onload的区别
- java泛型的使用
- js判断汉字字数
- IOS开发之不同版本适配问题2(#ifdef __IPHONE_7_0)(转载)
- Linux文件系统介绍
- JavaScript函数柯里化的一些思考
- JDBC连接SQLServer的几种方式
- MultipartEntityBuilder.addTextBody 中文乱码
- nginx与ios实现https双向认证
- 加盟全景-加盟VR虚拟现实-全景智慧城市
- Pivot Table系列之切片器 (Slicer)
- 解决linux 乌班图下使用eclipse创建类和其他各种操作进程卡死的问题的一种可能方法
- 微信和QQ内置浏览器为什么老是弹停止访问该网页,微信域名被屏蔽的解决办法
- windows搭建zabbix agent
- Java 关键字 速查表
- 7 Make vs Do
- Netty 4.1 Getting Start (翻译) + Demo