Resolves Negative Subarray Task
This commit is contained in:
parent
3da2a03859
commit
1279712a8f
2 changed files with 58 additions and 0 deletions
|
@ -0,0 +1,30 @@
|
||||||
|
package eu.ztsh.training.hackerrank.datastructures.subarray;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStreamReader;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Java Subarray task.
|
||||||
|
* source: https://www.hackerrank.com/challenges/java-negative-subarray/problem
|
||||||
|
*/
|
||||||
|
public class Solution {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
var reader = new BufferedReader(new InputStreamReader(System.in));
|
||||||
|
var n = Integer.parseInt(reader.readLine());
|
||||||
|
var array = Arrays.stream(reader.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
|
||||||
|
var counter = new AtomicInteger(0);
|
||||||
|
IntStream.range(0, n).forEach(begin -> IntStream.range(begin, n + 1)
|
||||||
|
.forEach(end -> {
|
||||||
|
if (Arrays.stream(array, begin, end).sum() < 0) {
|
||||||
|
counter.incrementAndGet();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
System.out.println(counter.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,28 @@
|
||||||
|
package eu.ztsh.training.hackerrank.datastructures.subarray;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import eu.ztsh.training.hackerrank.HackerRankTest;
|
||||||
|
import eu.ztsh.training.hackerrank.SolutionClassDescription;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
@DisplayName("HackerRank challenges: Java Subarray")
|
||||||
|
class SolutionTest extends HackerRankTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testCase0() {
|
||||||
|
simpleAssert(
|
||||||
|
List.of("5", "1 -2 4 -5 1"),
|
||||||
|
List.of("9")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected SolutionClassDescription getSolutionClassDescription() {
|
||||||
|
return new SolutionClassDescription(Solution.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue