[英]How to find minimum in subarray in java
I had an exam which I failed to display it.我有一个考试,但我没能展示出来。
Kindly help how to achieve this请帮助如何实现这一目标
Given an array A[] of size N and an integer k.给定一个大小为 N 的数组 A[] 和一个整数 k。 Task is to print the minimum element for each subarray of size k.
任务是打印每个大小为 k 的子数组的最小元素。
For Each valid index i(0<=i <=N -K) Have to print min(A[i],A[i+1],A[i+2]...A[i+k]).
Input format: The first line will coontains two integers N and k.输入格式:第一行将包含两个整数 N 和 k。 The second line contain N intgers denoting the elements of Array A[]
第二行包含 N 个整数,表示数组 A[] 的元素
Constraints:约束:
1 <=N <=10^5
1<=K <= N
1<=A[i] <=10^6
Output Format print the minimum elements for each subarray of size k separated by space.输出格式打印每个由空格分隔的大小为 k 的子数组的最小元素。
input:输入:
5 2
10 0 3 2 5
output:输出:
0 0 2 2
But what I tried is find maximum element:但我尝试的是找到最大元素:
I know this is wrong.我知道这是错误的。 But I know only this.
但我只知道这一点。
public static int maxSum(int arr[], int n, int k)
{
// k must be greater
if (n < k)
{
System.out.println("Invalid");
return -1;
}
// Compute sum of first window of size k
int res = 0;
for (int i=0; i<k; i++)
res += arr[i];
// Compute sums of remaining windows by
// removing first element of previous
// window and adding last element of
// current window.
int curr_sum = res;
for (int i=k; i<n; i++)
{
curr_sum += arr[i] - arr[i-k];
res = Math.max(res, curr_sum);
}
return res;
}
/* Driver program to test above function */
public static void main(String[] args)
{
int arr[] = {5,2,10,0,3,2,5};
int k = 7;
int n = arr.length;
System.out.println(maxSum(arr, n, k));
}
}
This is a super-straightforward solution I wrote in about 5 minutes.这是我在大约 5 分钟内编写的一个超级简单的解决方案。 Note I don't perform the input, the
n
, k
, array
values are just hardcoded in main
method.注意我不执行输入,
n
, k
, array
值只是在main
方法中硬编码。
package stackoverflow;
public class MinimumSubArray {
public static void main(String[] args) {
solve(5, 2, new int[]{ 10, 0, 3, 2, 5 }); // expect 0 0 2 2
solve(5, 2, new int[]{ 10, 0, 3, 2, 1 }); // expect 0 0 2 1
solve(1, 1, new int[]{ 6 }); // expect 6
solve(3, 3, new int[]{ 3, 2, 1 }); // expect 1
solve(3, 1, new int[]{ 3, 2, 1 }); // expect 3 2 1
}
private static void solve(final int n, final int k, final int[] array) {
if (n != array.length)
throw new IllegalArgumentException( String.format("Array length must be %d.", n) );
if (k > n)
throw new IllegalArgumentException( String.format("K = %d is bigger than n = %d.", k, n) );
int currentStartIndex = 0;
while (currentStartIndex <= (n - k)) {
int min = array[currentStartIndex];
for (int i = currentStartIndex + 1; i < currentStartIndex + k; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.printf("%d ", min); // print minimum of the current sub-array
currentStartIndex++;
}
System.out.println();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.