lintcode-41. Maximum Subarray
程序员文章站
2022-03-24 17:41:20
...
1. 问题描述
Description
Given an array of integers, find a contiguous subarray which has the largest sum.
The subarray should contain at least one number.
2. my solution
2.1 我的思路
因为是连续的, 所以想到位置不断向前移动,和小于0更新位置, 记录最大和的方法
2.2 代码实现
public class Solution {
/**
* @param nums: A list of integers
* @return: A integer indicate the sum of max subarray
*/
public int maxSubArray(int[] nums) {
// write your code here
int sum = 0;
int maxSum = nums[0];
for (int i = 0;i<nums.length ;i++ )
{
sum += nums[i];
if(sum>maxSum)
maxSum = sum;
else if(sum<=0) sum = 0;
}
return maxSum;
}
}
2.3 运行结果
3. others solutions
3.1 思路一(较好)
public class Solution {
public int maxSubArray(int[] A) {
if (A == null || A.length == 0){
return 0;
}
//max记录全局最大值,sum记录前i个数的和,minSum记录前i个数中0-k的最小值
int max = Integer.MIN_VALUE, sum = 0, minSum = 0;
for (int i = 0; i < A.length; i++) {
sum += A[i];
max = Math.max(max, sum - minSum);
minSum = Math.min(minSum, sum);
}
return max;
}
}
推荐阅读
-
最高内部数据传输率(Maximum Internal Data Transfer Rate)
-
oracle 导入报错:field in data file exceeds maximum length
-
解决PHP mysql_query执行超时(Fatal error: Maximum execution time …)
-
【学习笔记】RMQ-Range Minimum/Maximum Query (区间最小/最大值)
-
lintcode-741. Calculate Maximum Value II题解
-
自适应布局meta标签中viewport、content、width、initial-scale、minimum-scale、maximum-scale总结
-
[cf] 1401 D.Maximum Distributed Tree
-
Codeforces Round #665 (Div. 2) D. Maximum Distributed Tree(dfs)
-
LeetCode------Maximum SubArray
-
leetcode【53】Maximum Subarray