fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. int n = 3;
  12. long[] req = {1, 2, 3};
  13. long[] stock = {10, 12, 14};
  14. long[] cost = {2, 3, 5};
  15. long budget = 100;
  16.  
  17. long result = findMaxProducible(n, req, stock, cost, budget);
  18.  
  19. System.out.println("Maximum number of units that can be produced: " + result);
  20. }
  21. public static long findMaxProducible(int n, long[] req, long[] stock, long[] cost, long budget) {
  22. long low = 0;
  23. long high = (long) 2e18;
  24. long maxUnits = 0;
  25.  
  26. while (low <= high) {
  27. long mid = low + (high - low) / 2;
  28.  
  29. if (mid == 0) {
  30. low = mid + 1;
  31. continue;
  32. }
  33.  
  34. long currentCost = 0;
  35. boolean possible = true;
  36.  
  37. for (int i = 0; i < n; i++) {
  38. long requiredAmount = req[i] * mid;
  39. long amountToBuy = 0;
  40.  
  41. if (requiredAmount > stock[i]) {
  42. amountToBuy = requiredAmount - stock[i];
  43. }
  44.  
  45. if (cost[i] > 0 && amountToBuy > (Long.MAX_VALUE - currentCost) / cost[i]) {
  46. currentCost = Long.MAX_VALUE;
  47. break;
  48. }
  49. currentCost += amountToBuy * cost[i];
  50.  
  51. if (currentCost > budget) {
  52. break;
  53. }
  54. }
  55.  
  56. if (currentCost <= budget) {
  57. maxUnits = mid;
  58. low = mid + 1;
  59. } else {
  60. high = mid - 1;
  61. }
  62. }
  63.  
  64. return maxUnits;
  65. }
  66. }
Success #stdin #stdout 0.1s 55684KB
stdin
Standard input is empty
stdout
Maximum number of units that can be produced: 9