


In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query
We have two arrays of integers, one with calculated elements and the other with the split points required to split the array to generate subsets, we have to calculate each subset in each split The sum of and returns the maximum subset
Let us understand through an example:-
Input− int arr[] = int arr[] = { 9, 4, 5, 6, 7 } int splitPoints[] = { 0, 2, 3, 1 };
Output− The maximum subarray sum after each split [22, 13, 9 , 9]
Explanation− Here we decompose the array according to its split points, and obtain the maximum subset sum after each split
First After the second split strong> → {9} and {4,5,6,7} >> The maximum subarray sum is - 22
After the second split → {9} , {4,5} and {6,7} >> The maximum subarray sum is - 13
After the third split →{9}, {4,5}, { 6} and {7} >> The maximum subarray sum is - 9
After the fourth split →{9}, {4}, {5}, {6} and { 7} >> Maximum subarray sum is- 9
input−int arr[] = int arr[] = { 7, 8, 5, 9, 1 } int splitPoints[] = { 1, 2, 0, 3 };
Output−The maximum subarray sum after each division [15, 115, 10, 9]
Explanation−Here we decompose the array according to its split points, and obtain the maximum subset sum after each split
After the first split → {7, 8} and {5,9,1} >> The maximum subarray sum is 15
After the second split → {7,8}, {5} and {9,1 } >> The maximum sub-array sum is 115
After the third split →{7}, {8}, {5} and {9,1} >> The maximum sub-array sum is 10
After the fourth split →{7}, {8}, {5}, {9} and {1} >> the maximum sub-array sum is 9
The methods used in the following program are as follows -
-
We will start from the main() method
Enter the array of any given length , such as arr[] and splitPoints[]. Their lengths are calculated and passed to the method in the form calculateSubsetSum(arr.length, splitPoints.length, splitPoints, arr).
-
In the method calculateSubsetSum()
Create an integer array as sum[] and set sum[0 ] is set to arr[0].
Start looping FOR from i to 1 until the length of the array, and set sum[i] to sum[i - 1] arr[i] and set temp[0] to new subSets(0, n - 1, sum[n - 1]).
Continue to add t2.add(temp[0]) and t1.add(0)
Start looping FOR from i to 0, up to the length of the splitPoints array. Inside the loop set currentSplitPoint to t1.floor(splitPoints[i]) and remove from t2 to t2.remove(temp[currentSplitPoint])
Set end to temp[currentSplitPoint ] .last and temp[currentSplitPoint] as new subSets(currentSplitPoint, splitPoints[i], sum[splitPoints[i]] - (currentSplitPoint == 0 ? 0 : sum[currentSplitPoint - 1]))
Use t2.add(temp[currentSplitPoint]) and temp[splitPoints[i] 1] = new subSets(splitPoints[i] 1, end, sum[end] - sum[splitPoints[i] add] ])
- ##Use t2.add(temp[splitPoints[i] 1]), t1.add(currentSplitPoint) and t1.add(splitPoints[i] to add 1)
- Print t2.first() value.
- Create a class subSets and declare first, last and value as its data members and define the default constructor as subSets(int f, int l, int v), and set first to f, last to l, and value to v
- Create a class as utilityComparator, which will implement Comparator
- Create a public method as a comparison and check IF s2.value is not equal to s1.value, then return s2.value - s1.value.
- Check whether s1.first is not equal to s2.first, and then return s2.first - s1.first
p>
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
class utilityComparator implements Comparator<subSets>{
public int compare(subSets s1, subSets s2){
if(s2.value != s1.value){
return s2.value - s1.value;
}
if(s1.first != s2.first){
return s2.first - s1.first;
}
return 0;
}
}
class subSets{
int first;
int last;
int value;
subSets(int f, int l, int v){
first = f;
last = l;
value = v;
}
}
public class testClass{
static void calculateSubsetSum(int n, int k, int splitPoints[], int arr[]){
int sum[] = new int[n];
sum[0] = arr[0];
for (int i = 1; i < n; i++){
sum[i] = sum[i - 1] + arr[i];
}
TreeSet<Integer> t1 = new TreeSet<>();
TreeSet<subSets> t2 = new TreeSet<>(new utilityComparator());
subSets temp[] = new subSets[n];
temp[0] = new subSets(0, n - 1, sum[n - 1]);
t2.add(temp[0]);
t1.add(0);
System.out.println("Maximum subarray sum after each split");
for (int i = 0; i < k; i++){
int currentSplitPoint = t1.floor(splitPoints[i]);
t2.remove(temp[currentSplitPoint]);
int end = temp[currentSplitPoint].last;
temp[currentSplitPoint] = new subSets(currentSplitPoint, splitPoints[i], sum[splitPoints[i]] - (currentSplitPoint == 0 ? 0 : sum[currentSplitPoint - 1]));
t2.add(temp[currentSplitPoint]);
temp[splitPoints[i] + 1] = new subSets(splitPoints[i] + 1, end, sum[end] - sum[splitPoints[i]]);
t2.add(temp[splitPoints[i] + 1]);
t1.add(currentSplitPoint);
t1.add(splitPoints[i] + 1);
System.out.println(t2.first().value);
}
}
public static void main(String[] args){
int arr[] = { 2, 1, 6, 8, 5, 10, 21, 13};
int splitPoints[] = { 3, 1, 2, 0, 4, 5 };
calculateSubsetSum(arr.length, splitPoints.length, splitPoints, arr);
}
}
OutputIf we run the above code it will generate the following outputMaximum subarray sum after each split 49 49 49 49 44 34
The above is the detailed content of In Java, find the maximum subarray sum of subarrays after splitting an array into subarrays based on a given query. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
