leetCode- Maximum Subarray
来源:互联网 发布:知左手边那个字怎么读 编辑:程序博客网 时间:2024/06/13 09:46
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
普通版:
class Solution { public int maxSubArray(int[] nums) { int sum = 0; int max = Integer.MIN_VALUE; int len = nums.length; for(int i = 0;i < len;i++){ if(sum < 0){ sum = nums[i]; }else{ sum += nums[i]; } if(sum > max){ max = sum; } } return max; }}
改进版(Math.max()函数的用法很巧妙):
class Solution { public int maxSubArray(int[] nums) { int max = nums[0]; int sum = nums[0]; for (int i = 1; i < nums.length; i++) { sum = Math.max(sum + nums[i], nums[i]); max = Math.max(sum, max); } return max; }}
阅读全文
0 0
- 【LeetCode】Maximum Subarray 和 Maximum Product Subarray
- LeetCode: Maximum Subarray
- LeetCode Maximum Subarray
- [Leetcode] Maximum Subarray
- LeetCode: Maximum Subarray
- leetcode 25: Maximum Subarray
- [LeetCode] Maximum Subarray
- [Leetcode] Maximum Subarray
- [LeetCode]Maximum Subarray
- [leetcode]Maximum Subarray
- LeetCode-Maximum Subarray
- [leetcode] Maximum Subarray
- LeetCode 45: Maximum Subarray
- LeetCode - Maximum Subarray
- LeetCode:Maximum Subarray
- LeetCode 53: Maximum Subarray
- 【leetcode】Maximum Subarray
- Leetcode Maximum Subarray
- 数据结构关于栈的选择题
- pacemaker实现apache高可用
- LPWAN战火不止 封闭区域LoRa更具优势
- Bi-shoe and Phi-shoe
- 改变android状态栏颜色
- leetCode- Maximum Subarray
- float、double计算中精度丢失的处理
- Ubuntukylin16.04.2下anaconda2与anaconda3共存
- Android AIDL双向通信
- 走向程序猿的第一步
- poi导出word
- bzoj 3944 Sum 杜教筛
- css设置小图标
- Linux的帧缓冲(Frame Buffer)之一:原理及控制参数