Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private int sumBalance(int[] nums, int startIndex, int endIndex, int lastStartIndex, int lastEndIndex,
- int lastCount) {
- int sum = lastCount;
- if (startIndex < lastStartIndex) {
- for (; startIndex < lastStartIndex; startIndex++) {
- sum += nums[startIndex];
- }
- } else if (startIndex > lastStartIndex) {
- for (; startIndex > lastStartIndex; lastStartIndex++) {
- sum -= nums[lastStartIndex];
- }
- }
- if (endIndex > lastEndIndex) {
- for (; lastEndIndex < endIndex; lastEndIndex++) {
- sum += nums[lastEndIndex];
- }
- } else if (endIndex < lastEndIndex) {
- for (; endIndex < lastEndIndex; endIndex++) {
- sum -= nums[endIndex];
- }
- }
- if (sum == 0) {
- for (; startIndex < endIndex; startIndex++) {
- sum += nums[startIndex];
- }
- }
- return sum;
- }
- private boolean checkBalance(int[] nums, int leftStart, int leftEnd, int lastLeftStartIndex, int lastLeftEndIndex, int lastLeftCount,
- int rightStart, int rightEnd, int lastRightStartIndex, int lastRightEndIndex, int lastRightCount, boolean leftWasMore) {
- if (nums.length < 2) return false;
- int sumLeft = sumBalance(nums, leftStart, leftEnd, lastLeftStartIndex, lastLeftEndIndex, lastLeftCount);
- int sumRight = sumBalance(nums, rightStart, rightEnd, lastRightStartIndex, lastRightEndIndex, lastRightCount);
- if (sumLeft < sumRight) {
- if (leftWasMore) return false;
- return checkBalance(nums, leftStart, leftEnd + 1, lastLeftStartIndex, leftEnd, sumLeft,
- rightStart + 1, rightEnd, rightStart, rightEnd, sumRight, false);
- } else if (sumLeft > sumRight) {
- return checkBalance(nums, leftStart, leftEnd - 1, lastLeftStartIndex, leftEnd, sumLeft,
- rightStart - 1, rightEnd, rightStart, rightEnd, sumRight, true);
- }
- return true;
- }
- public boolean canBalance(int[] nums) {
- return checkBalance(nums, 0, nums.length/ 2, 0, nums.length/ 2, 0,
- nums.length/ 2, nums.length, nums.length / 2, nums.length, 0, false);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement