forked from xieqilu/Qilu-leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.MaxSubArraySum.cs
More file actions
103 lines (93 loc) · 2.3 KB
/
Copy path28.MaxSubArraySum.cs
File metadata and controls
103 lines (93 loc) · 2.3 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//Find the Contiguous subarray within an array(containing at least one number)
//which has the largest sum.
/**
* 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.
Edge case: all elements in the array are negative value;
*/
using System;
using System.Collections;
namespace MaxSubArraySum
{
public class Finder
{
public static bool IsAllNegative(int[] a)
{
foreach (int e in a) { //O(n)
if (e > 0)
return false;
}
return true;
}
public static int FindLargestSumEasy(int[] a){
//handle edge case: all elements are negative
if (IsAllNegative (a)) {
int max = a [0];
foreach (int i in a) {
if (i > max)
max = i;
}
return max;
}
int currentMax = 0, finalMax = 0;
foreach (int i in a) {
if (i < 0) {
currentMax = currentMax + i;
if (currentMax < 0)
currentMax = 0;
} else {
currentMax = currentMax + i;
if (currentMax > finalMax)
finalMax = currentMax;
}
}
return finalMax;
}
//solution1
public static int FindLargestSum(int[] a) //time: O(n) space: O(1)
{
if (!IsAllNegative (a)) {
int MaxSoFar = 0, MaxHere = 0;
foreach (int e in a) { //O(n)
MaxHere = MaxHere + e;
MaxHere = Max (MaxHere, 0);
if(MaxHere >0)
MaxSoFar = Max (MaxHere, MaxSoFar);
}
return MaxSoFar;
} else {
int max = a [0];
for (int i=0;i<a.Length;i++) { //O(n)
max = Max (max, a [i]);
}
return max;
}
}
private static int Max(int first, int second)
{
return (first > second) ? first : second;
}
//solution2
public static int FindLargestSumSimple(int[] a)//time: O(n) space: O(1)
{
int MaxSoFar = a [0];
int MaxHere = a [0];
for (int i = 1; i < a.Length; i++) {
MaxHere = Max (a [i], MaxHere + a [i]);
MaxSoFar = Max (MaxHere, MaxSoFar);
}
return MaxSoFar;
}
}
class MainClass
{
public static void Main (string[] args)
{
int[] test = new int[6]{ 2, -4, -4, 5, 9, 3 };
Console.WriteLine (Finder.FindLargestSum (test));
Console.WriteLine (Finder.FindLargestSumSimple (test));
Console.WriteLine (Finder.FindLargestSumEasy (test));
}
}
}