th0m45s5helby

Untitled

Sep 14th, 2021
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.Math;
  3. class Main {
  4.     static long maximumSum_simplified(int[] A) {
  5.         int len = A.length;
  6.  
  7.         long[] maxSum = new long[len + 1];
  8.  
  9.         for (int start = 0, end; start < len - 1; start = end) {
  10.             end = start + 1;
  11.             if (A[end] <= A[start]) {
  12.                 while (end + 1 < len && A[end + 1] <= A[end]) end++;
  13.                 for (int i = Math.max(end - 1, start + 1); i <= end; i++) {
  14.                     maxSum[i + 1] = Math.max(maxSum[start] + A[start] - A[i],
  15.                             maxSum[start + 1] + A[start + 1] - A[i]);
  16.                 }
  17.             } else {
  18.                 while (end + 1 < len && A[end + 1] >= A[end]) end++;
  19.                 for (int i = Math.max(end - 1, start + 1); i <= end; i++) {
  20.                     maxSum[i + 1] = Math.max(maxSum[start] + A[i] - A[start],
  21.                             maxSum[start + 1] + A[i] - A[start + 1]);
  22.                 }
  23.             }
  24.         }
  25.  
  26.         return maxSum[len];
  27.     }
  28.   public static void main(String[] args) {
  29.  
  30.     int[] a={8,1,7,9,2};
  31.     System.out.println(maximumSum_simplified(a));
  32.    
  33.  
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment