p1_kadane_algo.cpp
· 1.2 KiB · C++
Исходник
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define INF 1e18
#define nl "\n"
#define pb push_back
#define eb emplace_back
/*Note: emplace_back is faster than push_back*/
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
long long maxSubarraySum(vector<int> &nums)
{
int n = nums.size();
long long mx = LONG_MIN; // maximum sum
long long sum = 0;
for (int i = 0; i < n; i++)
{
sum += nums[i];
if (sum > mx)
{
mx = sum;
}
if (sum < 0)
{
sum = 0;
}
}
return mx;
}
void solve()
{
}
int main()
{
// ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
ll t = 1;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
cin >> a[i];
cout << maxSubarraySum(a) << nl;
}
}
1 | #include <bits/stdc++.h> |
2 | using namespace std; |
3 | #define ll long long |
4 | #define mod 1000000007 |
5 | #define INF 1e18 |
6 | #define nl "\n" |
7 | #define pb push_back |
8 | #define eb emplace_back |
9 | /*Note: emplace_back is faster than push_back*/ |
10 | #define ppb pop_back |
11 | #define mp make_pair |
12 | #define ff first |
13 | #define ss second |
14 | #define PI 3.141592653589793238462 |
15 | #define set_bits __builtin_popcountll |
16 | #define sz(x) ((int)(x).size()) |
17 | #define all(x) (x).begin(), (x).end() |
18 | |
19 | long long maxSubarraySum(vector<int> &nums) |
20 | { |
21 | int n = nums.size(); |
22 | long long mx = LONG_MIN; // maximum sum |
23 | long long sum = 0; |
24 | |
25 | for (int i = 0; i < n; i++) |
26 | { |
27 | |
28 | sum += nums[i]; |
29 | |
30 | if (sum > mx) |
31 | { |
32 | mx = sum; |
33 | } |
34 | |
35 | if (sum < 0) |
36 | { |
37 | sum = 0; |
38 | } |
39 | } |
40 | |
41 | return mx; |
42 | } |
43 | void solve() |
44 | { |
45 | } |
46 | int main() |
47 | { |
48 | // ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); |
49 | #ifndef ONLINE_JUDGE |
50 | // freopen("input.txt", "r", stdin); |
51 | // freopen("output.txt", "w", stdout); |
52 | #endif |
53 | |
54 | ll t = 1; |
55 | cin >> t; |
56 | while (t--) |
57 | { |
58 | int n; |
59 | cin >> n; |
60 | vector<int> a(n); |
61 | for (int i = 0; i < n; i++) |
62 | cin >> a[i]; |
63 | cout << maxSubarraySum(a) << nl; |
64 | } |
65 | } |