Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution{
- private static int INCREASING = 1;
- private static int DECREASING = 2;
- private static int CONSTANT = 3;
- public int solution(int[] A){
- int currentMonotonousness = checkTypeOfSubsequence(0, A);
- int lengthOfSubsequence = 1;
- int numberOfSubseqences = 0;
- for(int i = 0; i < A.length-1; i++){
- if (checkIfNumberOfSubseqnecuesIsToBig(numberOfSubseqences)) return -1;
- if(!isChangeOfMonotonousness(currentMonotonousness, i, A)){
- lengthOfSubsequence++;
- }
- else{
- numberOfSubseqences += calculateNumberOfSubseqnuences(lengthOfSubsequence);
- currentMonotonousness = checkTypeOfSubsequence(i, A);
- if(!isEndOfArray(i, A.length)) lengthOfSubsequence = 2;
- }
- }
- numberOfSubseqences += calculateNumberOfSubseqnuences(lengthOfSubsequence);
- return numberOfSubseqences;
- }
- private boolean isChangeOfMonotonousness(int currentMonotonousness, int index, int[] array){
- return currentMonotonousness != checkTypeOfSubsequence(index, array);
- }
- private boolean isEndOfArray(int index, int arrayLength){
- return index == arrayLength - 2;
- }
- private int checkTypeOfSubsequence(int index, int[] array){
- int differential = array[index+1] - array[index];
- if(differential > 0){
- return INCREASING;
- }
- else if(differential < 0){
- return DECREASING;
- }
- else
- return CONSTANT;
- }
- private int calculateNumberOfSubseqnuences(int length){
- int result = 0;
- for(int i = length - 1; i > 0; i--){
- result += i;
- }
- return result;
- }
- private boolean checkIfNumberOfSubseqnecuesIsToBig(int sum){
- return sum > 1000000000;
- }
- public static void main(String[] args){
- Solution solution = new Solution();
- int result = solution.solution(new int[]{1,3,4,4,5,5,0});
- System.out.println(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement