Advertisement
Guest User

Untitled

a guest
Oct 25th, 2014
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. class Solution {
  2. public int solution(int[] A) {
  3. // Find index of all peaks
  4. HashSet<Integer> peak_indexes = new HashSet<Integer>();
  5. for (int i = 1; i < A.length - 1; i++) {
  6. int left = A[i - 1];
  7. int center = A[i];
  8. int right = A[i + 1];
  9. if (left < center && center > right) {
  10. peak_indexes.add(i);
  11. }
  12. }
  13.  
  14. int len = A.length;
  15. int max_blocks = len / 3;
  16. int blocks = 1;
  17. int max_num_blocks = 0;
  18. while(blocks <= max_blocks) {
  19. if (len % blocks == 0) {
  20. int block_size = len / blocks;
  21. boolean valid = true;
  22. for (int i = 0; i <= len - block_size; i += block_size) {
  23. boolean block_valid = false;
  24. for (int j = i; j < i + block_size; j++) {
  25. if (peak_indexes.contains(j)) {
  26. block_valid = true;
  27. break;
  28. }
  29. }
  30. if (!block_valid) {
  31. valid = false;
  32. break;
  33. }
  34. }
  35. if (valid) {
  36. max_num_blocks = blocks;
  37. }
  38. }
  39. blocks++;
  40. }
  41.  
  42. return max_num_blocks;
  43. }
  44.  
  45. }
  46.  
  47. A[0] = 1
  48. A[1] = 2
  49. A[2] = 3
  50. A[3] = 4
  51. A[4] = 3
  52. A[5] = 4
  53. A[6] = 1
  54. A[7] = 2
  55. A[8] = 3
  56. A[9] = 4
  57. A[10] = 6
  58. A[11] = 2
  59.  
  60. A[0], A[1], ..., A[K − 1],
  61. A[K], A[K + 1], ..., A[2K − 1],
  62. ...
  63. A[N − K], A[N − K + 1], ..., A[N − 1].
  64.  
  65. one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks.
  66. two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak.
  67. three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block.
  68.  
  69. class Solution { public int solution(int[] A); }
  70.  
  71. A[0] = 1
  72. A[1] = 2
  73. A[2] = 3
  74. A[3] = 4
  75. A[4] = 3
  76. A[5] = 4
  77. A[6] = 1
  78. A[7] = 2
  79. A[8] = 3
  80. A[9] = 4
  81. A[10] = 6
  82. A[11] = 2
  83.  
  84. N is an integer within the range [1..100,000];
  85. each element of array A is an integer within the range [0..1,000,000,000].
  86.  
  87. expected worst-case time complexity is O(N*log(log(N)));
  88. expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement