数组如何在java中找到子数组中的最小值
我有一次考试没能显示出来
请帮助我们如何做到这一点
给定一个大小为N的数组A[]和一个整数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]).
输入格式: 第一行包含两个整数N和k。 第二行包含N个整数,表示数组A[]的元素
限制条件:
1 <=N <=10^5
1<=K <= N
1<=A[i] <=10^6
输出格式 打印大小为k的每个子阵列的最小元素,以空格分隔
输入:
5 2
10 0 3 2 5
输出:
0 0 2 2
但我尝试的是找到最大元素:
我知道这是错误的。但我只知道这一点
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));
}
}
共 (0) 个答案