|
| 1 | +package com.doublejony.leetcode; |
| 2 | + |
| 3 | +import com.google.common.base.Stopwatch; |
| 4 | +import com.tngtech.java.junit.dataprovider.DataProvider; |
| 5 | +import com.tngtech.java.junit.dataprovider.DataProviderRunner; |
| 6 | +import com.tngtech.java.junit.dataprovider.UseDataProvider; |
| 7 | +import org.junit.Test; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | + |
| 10 | +import static com.doublejony.common.AssertResolve.resolve; |
| 11 | + |
| 12 | +@RunWith(DataProviderRunner.class) |
| 13 | +public class Leet2145 { |
| 14 | + |
| 15 | + @DataProvider |
| 16 | + public static Object[][] testCase() { |
| 17 | + // @formatter:off |
| 18 | + return new Object[][] { |
| 19 | + { |
| 20 | + new int[] {1, -3, 4}, |
| 21 | + 1, |
| 22 | + 6, |
| 23 | + 2 |
| 24 | + }, |
| 25 | + { |
| 26 | + new int[] {3, -4, 5, 1, -2}, |
| 27 | + -4, |
| 28 | + 5, |
| 29 | + 4 |
| 30 | + }, |
| 31 | + { |
| 32 | + new int[] {4, -7, 2}, |
| 33 | + 3, |
| 34 | + 6, |
| 35 | + 0 |
| 36 | + } |
| 37 | + }; |
| 38 | + // @formatter:on |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + @UseDataProvider("testCase") |
| 43 | + public void solution(int[] differences, int lower, int upper, long expected) { |
| 44 | + |
| 45 | + Stopwatch timer = Stopwatch.createStarted(); |
| 46 | + resolve(Thread.currentThread().getStackTrace()[1].getMethodName(), expected, |
| 47 | + new Solution().numberOfArrays(differences, lower, upper), timer.stop()); |
| 48 | + } |
| 49 | + |
| 50 | + class Solution { |
| 51 | + public int numberOfArrays(int[] differences, int lower, int upper) { |
| 52 | + long a = 0; |
| 53 | + long max = 0; |
| 54 | + long min = 0; |
| 55 | + for (int d : differences) { |
| 56 | + a += d; |
| 57 | + max = Math.max(max, a); |
| 58 | + min = Math.min(min, a); |
| 59 | + } |
| 60 | + return (int) Math.max((upper - lower) - (max - min) + 1, 0); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments