LeetCode
来源:互联网 发布:淘宝店铺介绍文艺句子 编辑:程序博客网 时间:2024/06/06 14:21
53. Maximum Subarray Problem's Link
Problem's Link
----------------------------------------------------------------------------
Mean:
最大子段和.
analyse:
dp.
Time complexity: O(N)
view code
/**
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
* Author: crazyacking
* Date : 2016-03-21-11.15
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long(LL);
typedef unsigned long long(ULL);
const double eps(1e-8);
class Solution
{
public:
int maxSubArray(vector<int>& nums)
{
if(!nums.size())
return 0;
int res=0,sum=0;
int maxVal=INT_MIN;
for(int i=0;i<nums.size();++i)
{
sum+=nums[i];
if(sum<0)
sum=0;
maxVal=max(maxVal,nums[i]);
res=max(res,sum);
}
if(maxVal<0) res=maxVal;
return res;
}
};
int main()
{
int n;
while(cin>>n)
{
vector<int> nums(n);
for(int i=0;i<n;++i)
cin>>nums[i];
Solution solution;
int ans=solution.maxSubArray(nums);
cout<<ans<<endl;
cout<<"----------------------"<<endl;
}
return 0;
}
/*
*/
* -----------------------------------------------------------------
* Copyright (c) 2016 crazyacking.All rights reserved.
* -----------------------------------------------------------------
* Author: crazyacking
* Date : 2016-03-21-11.15
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long(LL);
typedef unsigned long long(ULL);
const double eps(1e-8);
class Solution
{
public:
int maxSubArray(vector<int>& nums)
{
if(!nums.size())
return 0;
int res=0,sum=0;
int maxVal=INT_MIN;
for(int i=0;i<nums.size();++i)
{
sum+=nums[i];
if(sum<0)
sum=0;
maxVal=max(maxVal,nums[i]);
res=max(res,sum);
}
if(maxVal<0) res=maxVal;
return res;
}
};
int main()
{
int n;
while(cin>>n)
{
vector<int> nums(n);
for(int i=0;i<n;++i)
cin>>nums[i];
Solution solution;
int ans=solution.maxSubArray(nums);
cout<<ans<<endl;
cout<<"----------------------"<<endl;
}
return 0;
}
/*
*/
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- LeetCode
- 单链表操作
- LeetCode
- python使用marshal模块序列化实例
- LeetCode
- LeetCode
- React 笔记4:Components and Props
- 台风路径模拟方法介绍
- LeetCode 61 Rotate List
- SQL
- java之集合13
- 在android的xml和java代码中使用透明度动画
- 抵制萨德抵制乐天--蠢货行为
- [Offer收割]编程练习赛3