coffeebeforecode

CSE2012 PP1 Q3

Aug 12th, 2021 (edited)
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. /*
  2. 3. Suppose an array A has n distinct integers. Write an algorithm to find an index k (k need not exist/ need not be unique) such that A[0].........A[k] is an increasing sequence and A[k+1]........A[n-1] is a decreasing sequence.
  3. Example:
  4. A = {5,4, 3, 2, 1} Here k=0, A[0] is an increasing sequence and A[1,4] = {4,3,2,1} is decreasing.
  5. A = {2, 4, 6, 5, 2, 1} then k can be 1 or 2.
  6. A = {1, 3, 5, 4, 6, 2} k does not exists
  7. */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. void solve(){
  13. unsigned int size;
  14. int *arr;
  15.  
  16. //Input
  17. printf("\nEnter the size of array: ");
  18. scanf("%u", &size);
  19. arr = (int *)malloc(sizeof(int)*size);
  20.  
  21. printf("\nInput values: ");
  22. int i;
  23. for(i = 0; i < size; i++){
  24. scanf("%d", &arr[i]);
  25. }
  26.  
  27. //Solving
  28.  
  29. int k = 0;
  30.  
  31. while(k < size && arr[k+1] > arr[k]){
  32. k++;
  33. }
  34.  
  35. /* //redundant
  36. if (k == size-1){
  37. printf("\nk=%d\n", k);
  38. return;
  39. }
  40. */
  41.  
  42. for(i = k+1; i < size; i++){
  43. if (arr[i]>arr[i-1]){
  44. printf("\nk does not exist\n");
  45. return;
  46. }
  47. }
  48.  
  49. printf("\nk=%d\n", k);
  50. }
  51.  
  52. int main(){
  53. solve();
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment