leetcode week18
来源:互联网 发布:物流线路规划软件 编辑:程序博客网 时间:2024/06/10 23:19
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
.
问题描述:给定一个数字串,找出和最大的子串。
解题思路:问题描述比较简单。对于一个数字串,从第一个开始逐个累计求和,求和结果与出现过的最大的和作比较,之后检查求和结果,若为0则将求和结果重置为0。最后输出最大和的值即可。注意开始的时候为了考虑只有一个元素或者数字全为负数的状况,不能将最大值的初始值设为0,设为nums[0]即可。注意要先与最大值比较之后再重置,要不然全是负数的话就会出问题。
class Solution {public: int maxSubArray(vector<int>& nums) { int max=nums[0]; int sum=0; for(int i=0; i<nums.size();i++){ sum+=nums[i]; if(sum>max){ max=sum; } if(sum<0){ sum=0; } } return max; }};
阅读全文
0 0
- Leetcode week18
- leetcode week18
- leetcode week18
- leetcode week18
- leetcode week18
- leetcode week18
- leetcode week18
- LeetCode Week18: Sicily Test
- 算法设计Week18 LeetCode Algorithms Problem #344 Integer Break
- week18- NO.128. Longest Consecutive Sequence
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- __construct,__destruct,__get,__set,__isset,__unset
- 经典蓝牙的配置文件攻略
- 概率图模型
- javaweb文件上传下载 视频转GIF
- iOS -- 置顶 点击 事件
- leetcode week18
- AD中PCB各层含义
- iOS端移动支付的一些坑
- Qt5解决中文乱码方法
- Android Service完全解析与实际运用
- mysql 分表分区策略
- 搭建LNMP环境(CentOS 6.8 + nginx1.10 + mysql5.6 + php5.6 )
- C语言函数返回类型为指针时的一些问题
- mysql之删除(删除、清空、删除重复数据)