generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem10.cs
More file actions
40 lines (35 loc) · 1.02 KB
/
Problem10.cs
File metadata and controls
40 lines (35 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/maximum-subarray/">Maximum Subarray</see>.
/// </summary>
public static class Problem10
{
/// <summary>
/// Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
/// Time complexity: O(n).
/// Space complexity: O(1).
/// </summary>
/// <param name="nums">Array to traverse.</param>
/// <returns>Largest subarray sum.</returns>
public static int MaxSubArray(int[] nums)
{
if (nums.Length == 0)
{
return 0;
}
var globalSum = nums[0];
for (int i = 1, currentSum = globalSum; i < nums.Length; i++)
{
if (currentSum < 0)
{
currentSum = nums[i];
}
else
{
currentSum += nums[i];
}
globalSum = Math.Max(globalSum, currentSum);
}
return globalSum;
}
}