|
| 1 | +import java.io.*; |
| 2 | +import java.math.*; |
| 3 | +import java.security.*; |
| 4 | +import java.text.*; |
| 5 | +import java.util.*; |
| 6 | +import java.util.concurrent.*; |
| 7 | +import java.util.regex.*; |
| 8 | + |
| 9 | +public class Solution { |
| 10 | + |
| 11 | + static int maxSubsetSum(int[] arr) { |
| 12 | + |
| 13 | + // O(n) Time, O(1) Space. Keep track of current max, notice that we could add first item or not. |
| 14 | + |
| 15 | + if (arr.length == 0) return 0; |
| 16 | + if (arr.length == 1) return Math.max(0, arr[0]); |
| 17 | + |
| 18 | + arr[0] = Math.max(0, arr[0]); |
| 19 | + arr[1] = Math.max(arr[0], arr[1]); |
| 20 | + |
| 21 | + for (int i = 2; i < arr.length; i++) { |
| 22 | + |
| 23 | + arr[i] = Math.max(arr[i-1], arr[i] + arr[i-2]); |
| 24 | + |
| 25 | + } |
| 26 | + |
| 27 | + return arr[arr.length - 1]; |
| 28 | + } |
| 29 | + |
| 30 | + private static final Scanner scanner = new Scanner(System.in); |
| 31 | + |
| 32 | + public static void main(String[] args) throws IOException { |
| 33 | + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); |
| 34 | + |
| 35 | + int n = scanner.nextInt(); |
| 36 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 37 | + |
| 38 | + int[] arr = new int[n]; |
| 39 | + |
| 40 | + String[] arrItems = scanner.nextLine().split(" "); |
| 41 | + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); |
| 42 | + |
| 43 | + for (int i = 0; i < n; i++) { |
| 44 | + int arrItem = Integer.parseInt(arrItems[i]); |
| 45 | + arr[i] = arrItem; |
| 46 | + } |
| 47 | + |
| 48 | + int res = maxSubsetSum(arr); |
| 49 | + |
| 50 | + bufferedWriter.write(String.valueOf(res)); |
| 51 | + bufferedWriter.newLine(); |
| 52 | + |
| 53 | + bufferedWriter.close(); |
| 54 | + |
| 55 | + scanner.close(); |
| 56 | + } |
| 57 | +} |
0 commit comments