Advertisement
Spidey2182

Minimum Maximum Subarray Sum (Java)

Jul 5th, 2023 (edited)
589
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.84 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class TestClass {
  4.     public static void main(String args[] ) throws Exception {
  5.         Scanner sc = new Scanner(System.in);
  6.         int n = sc.nextInt();
  7.         int k = sc.nextInt();
  8.         int[] a = new int[n];
  9.         for (int i = 0; i < n; i++)
  10.             a[i] = sc.nextInt();
  11.  
  12.         long l = 1, r = (long)1e15, m;
  13.         while (l < r) {
  14.             m = (l + r) / 2;
  15.  
  16.             if (numberOfSubarrays(a, m) <= k)
  17.                 r = m;
  18.             else
  19.                 l = m + 1;
  20.         }
  21.  
  22.         System.out.println(r);
  23.     }
  24.  
  25.     static int numberOfSubarrays(int[] a, long sum) {
  26.         int ans = 0;
  27.         long curr = 0;
  28.         for (int x : a) {
  29.             if (x > sum)
  30.                 return Integer.MAX_VALUE; // Not possible
  31.             if (curr + x > sum) {
  32.                 ans++;
  33.                 curr = 0;
  34.             }
  35.             curr += x;
  36.         }
  37.    
  38.         return ans + 1;
  39.     }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement