Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Demo {
- public static void main(String[] args) {
- int[] longest_run;
- longest_run = new int[]{3, 2, -1, 2, 7};
- foo(longest_run);
- }
- public static int foo(int[] arr) {
- int longest_asc__ = 1;
- int start_index_asc = 0;
- int end_index_asc = 0;
- int longest_desc__ = 1;
- int start_index_desc = 0;
- int end_index_desc = 0;
- boolean flag;
- int longest_asc = 1;
- int longest_desc = 1;
- int sum = 0;
- //for asc
- for (int start = 0, left = 0; start < arr.length && left < arr.length - 1; ) {
- if (arr[left + 1] >= arr[left]) {
- left++;
- longest_asc++;
- } else {
- if (longest_asc > longest_asc__) {
- longest_asc__ = longest_asc;
- start_index_asc = start; //inclusive
- end_index_asc = left; //inclusive
- }
- start = left + 1;
- left = start;
- longest_asc = 1;
- }
- //reached to end
- if (left == arr.length - 1) {
- if (longest_asc > longest_asc__) {
- longest_asc__ = longest_asc;
- start_index_asc = start; //inclusive
- end_index_asc = left; //inclusive
- }
- }
- }
- //for desc
- for (int start = 0, left = 0; start < arr.length && left < arr.length - 1; ) {
- if (arr[left + 1] <= arr[left]) {
- left++;
- longest_desc++;
- } else {
- if (longest_desc > longest_desc__) {
- longest_desc__ = longest_desc;
- start_index_desc = start; //inclusive
- end_index_desc = left; //inclusive
- }
- start = left + 1;
- left = start;
- longest_desc = 1;
- }
- //reached to end
- if (left == arr.length - 1) {
- if (longest_desc > longest_desc__) {
- longest_desc__ = longest_desc;
- start_index_desc = start; //inclusive
- end_index_desc = left; //inclusive
- }
- }
- }
- if (longest_asc__ == longest_desc__) {
- if (start_index_asc < start_index_desc) {
- flag = true; //asc
- } else flag = false;
- } else if (longest_asc__ > longest_desc__) {
- flag = true;
- } else {
- flag = false;
- }
- if (flag)
- for (int i = start_index_asc; i <= end_index_asc; i++) {
- System.out.print(arr[i] + " ");
- sum += arr[i];
- }
- else {
- for (int i = start_index_desc; i <= end_index_desc; i++) {
- System.out.print(arr[i] + " ");
- sum += arr[i];
- }
- }
- // System.out.println();
- // System.out.println("sum " + sum);
- return sum;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement