HashMap or prefix sum to solve problems like “count subarrays with a given sum” or maximum subarray sum from a certain point.
O(n) to O(1) for fixed ranges.
public class SuffixSumExample
{
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
int[] suffix = new int[n];
suffix[n - 1] = arr[n - 1]; // last element
for (int i = n - 2; i >= 0; i--)
{
suffix[i] = arr[i] + suffix[i + 1]; // cumulative sum from end
}
// Print suffix sum array
System.out.println("Suffix Sum Array:");
for (int i = 0; i < n; i++)
{
System.out.print(suffix[i] + " ");
}
}
}
Suffix Sum Array: 15 14 12 9 5
public class SuffixRangeSum
{
public static void main(String[] args)
{
int[] arr = {1, 2, 3, 4, 5};
int n = arr.length;
int[] suffix = new int[n];
// Build suffix sum array
suffix[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
{
suffix[i] = arr[i] + suffix[i + 1];
}
// Query sum from index 2 to end
int l = 2; // start index
int sum = suffix[l];
System.out.println("Sum from index " + l + " to end is: " + sum);
}
}
Sum from index 2 to end is: 12
Try below programs using Suffix Sum Technique in Java:
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.