Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Time limit: 5000ms Memory limit: 256mb Description: Given an array A of positive integers and an integer number K, please find the shortest subarray whose
Time limit: 5000ms Memory limit: 256mb Description: Given an array A of positive integers and an integer number K, please find the shortest subarray whose sum of each elements is not smaller than K, and return its length. You need to design an efficient algorithm with a O(n) time complexity. Otherwise, you may exceed the time limit. -----------------------Copy the following code, complete it and submit----------------------- /* I,, am submitting the assignment for an individual project. I declare that the assignment here submitted is original except for source material explicitly acknowledged, the piece of work, or a part of the piece of work has not been submitted for more than one purpose (i.e. to satisfy the requirements in two different courses) without declaration. I also acknowledge that I am aware of University policy and regulations on honesty in academic work, and of the disciplinary guidelines and procedures applicable to breaches of such policy and regulations, as contained in the University website http://www.cuhk.edu.hk/policy/academichonesty/. It is also understood that assignments without a properly signed declaration by the student concerned will be graded as zero by the teacher(s). */ #include #include #define MAX_LEN 1024 * 1024 #define MAX_QUERIES 10240 int shortest_subarray(int a[], int n, int k) { // WRITE YOUR CODE HERE } // DO NOT MODIFY THE CODE BELOW int main() { int n, i; int Q; int result; int *a = (int *)malloc(MAX_LEN * sizeof(int)); int Ks[MAX_QUERIES]; scanf("%d", &n); scanf("%d", &Q); for (i = 0; i < n; i++) scanf("%d", &a[i]); for (i = 0; i < Q; i++) scanf("%d", &Ks[i]); for (i = 0; i < Q; i++) { result = shortest_subarray(a, n, Ks[i]); printf("%d ", result); } free(a); return 0; } -----------------------------------------End of Code----------------------------------------- Input: First line consists of two integers N and Q; Second line is an array A of N positive integers; Then Q lines follows: each of them is a target value K; 0 <= N <= 10^6, 0 <= Q <= 10^5 Output: Q lines: the i-th line is the length of the shortest subarray for the i-th K If there exist no subarray with sum at least K, return 0. Sample Input 1: 6 1 1 2 3 4 1 2 6 Sample Output 1: 2 Sample Input 2: 4 1 1 1 1 1 5 Sample Output 2: 0
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started