Untitled
import java.util.*; public class SystemVulnerabilityCalculator { public static int getSystemVulnerabilitySum(List<Integer> vulnerability) { int n = vulnerability.size(); long sum = 0; final int MOD = 1000000007; int[] leftExtent = new int[n]; int[] rightExtent = new int[n]; Stack<Integer> stack = new Stack<>(); // Calculating left extent for each position for (int i = 0; i < n; i++) { while (!stack.isEmpty() && vulnerability.get(stack.peek()) < vulnerability.get(i)) { stack.pop(); } leftExtent[i] = stack.isEmpty() ? i + 1 : i - stack.peek(); stack.push(i); } // Clear the stack for right extent calculation stack.clear(); // Calculating right extent for each position for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && vulnerability.get(stack.peek()) <= vulnerability.get(i)) { stack.pop(); } rightExtent[i] = stack.isEmpty() ? n - i : stack.peek() - i; stack.push(i); } // Compute contributions of each index for (int i = 0; i < n; i++) { long totalSegments = (long) leftExtent[i] * rightExtent[i]; long contribution = (long) vulnerability.get(i) * totalSegments; sum = (sum + contribution) % MOD; } return (int) sum; } public static void main(String[] args) { List<Integer> vulnerability = Arrays.asList(4, 2, 1, 2); System.out.println("Total System Vulnerability Sum: " + getSystemVulnerabilitySum(vulnerability)); // Expected output: 59 } }
Leave a Comment