FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Data-Structures-Algorithms/Arrays/sum.java at master · NILESHMITTAL/Data-Structures-Algorithms · GitHub
NILESHMITTAL
/
Data-Structures-Algorithms
Public
forked from
CodersForLife/Data-Structures-Algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
Data-Structures-Algorithms
/
Arrays
/
sum.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (41 loc) · 1.2 KB
Breadcrumbs
Data-Structures-Algorithms
/
Arrays
/
sum.java
Copy path
File metadata and controls
48 lines (41 loc) · 1.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
java
.
util
.*;
import
java
.
math
.*;
public
class
sum
{
static
void
printMaxSum
(
int
[]
arr
){
//1) For max continuous sub array
int
max_ending_here
=
0
;
int
max_so_far
=
Integer
.
MIN_VALUE
;
/*OR int max_so_far = arr[0];*/
for
(
int
x
:
arr
){
max_ending_here
=
Math
.
max
(
x
,
max_ending_here
+
x
);
max_so_far
=
Math
.
max
(
max_so_far
,
max_ending_here
);
}
System
.
out
.
print
(
max_so_far
);
//2) For max non-continuous sub array, order doesn't matter
Arrays
.
sort
(
arr
);
int
sum
=
0
;
//if there is none positive value in entire array
if
(
arr
[
arr
.
length
-
1
] <=
0
)
sum
=
arr
[
arr
.
length
-
1
];
//accumulate all positive values in entire array
else
{
for
(
int
x
:
arr
){
if
(
x
>
0
)
sum
+=
x
;
}
}
System
.
out
.
println
(
" "
+
sum
);
}
public
static
void
main
(
String
args
[] )
throws
Exception
{
Scanner
sc
=
new
Scanner
(
System
.
in
);
int
t
=
sc
.
nextInt
();
for
(
int
i
=
0
;
i
<
t
;
i
++) {
int
n
=
sc
.
nextInt
();
int
[]
arr
=
new
int
[
n
];
for
(
int
j
=
0
;
j
<
n
;
j
++) {
arr
[
j
] =
sc
.
nextInt
();
}
printMaxSum
(
arr
);
}
}
}
Back
|
FazBrowse Home
|
New Git URL