Pagini recente » Cod sursa (job #3233559) | Cod sursa (job #3227665) | Cod sursa (job #3264963) | Cod sursa (job #1093003) | Cod sursa (job #2480203)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
/*
* Find a subset of a set with the maximum sum and a minimum length of k.
* Give the start and last index of the set and the maximum sum.
*
* */
public class Secv {
public static void main(String[] args) throws IOException {
int n = 0;
int k = 0;
int bufferSize = 8*1024;
int [] sum = new int [50000];
int s = 0;
int max = 0;
int startIndex = 1;
int lastIndex = 0;
FileReader fr=null;
BufferedReader br=null;
try {
fr = new FileReader("secv2.in");
br = new BufferedReader(fr, bufferSize);
String line = br.readLine();
String [] lines = line.split(" ");
n = Integer.parseInt(lines[0]);
k = Integer.parseInt(lines[1]);
line = br.readLine();
lines = line.split(" ");
sum[0] = Integer.parseInt(lines[0]);
for(int i = 1 ;i < k; i++) {
sum[i] = sum[i-1] + Integer.parseInt(lines[i]);
}
s=max=sum[k-1];
lastIndex = k-1;
int auxIndex =0;
for(int i = k ;i < n; i++) {
sum[i] = sum[i-1] + Integer.parseInt(lines[i]);
if(sum[i] - sum[i-k] > s + Integer.parseInt(lines[i])) {
s = sum[i] - sum [i-k];
auxIndex = i - k + 2;
}else {
s+=Integer.parseInt(lines[i]);
}
if(s > max) {
max = s;
startIndex = auxIndex;
lastIndex = i+1;
}
}
PrintWriter writer = new PrintWriter("secv2.out");
writer.print(startIndex+" "+lastIndex+" "+max);
writer.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}