本文主要是介绍2022 Task 3 Fair Index Count,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Task 3
You are given two arrays A and B consisting of N integers each.
Index K is named fair if the four sums (A[0]+…+A[K-1]), (A[K]+…+A[N-1]), (B[0]+…+B[K-1]) and (B[K]+…+B[N-1]) are all equal.
In other words, K is the index where the two arrays A and B can be split( into two non-empty arrays each) in such a way that the sums of the resulting arrays’ elements are equal.
For example, given arrays A = [0, 4, -1, 0, 3] and B = [0, -2, 5, 0, 3], index K=3 is fair. The sum of the four subarrays are all equals to 3. On the other hand, index K=2 is not fair, the sums of subarrays are not equal.
Write a function:
class Solution { public int solution(int[] A, int[] B); }
which, given two arrays of integers A and B, returns the total number of fair indexes.
Examples
- Given A = [0, 4, -1, 0, 3] and B = [0, -2, 5, 0, 3], your function should return 2. The fair indexes are 3 and 4. In both cases, the sums of elements of the subarrays are equals to 3.
- Given A = [2, -2, -3, 3] and B = [0, 0, 4, -4], your function should return 1. The only fair index is 2. Index 4 is not fair as the subarrays containing indexes from K to N-1 would be empty.
- Given A = [4, -1, 0, 3] and B = [-2, 6, 0, 4], your function should return 0. There are no fair indexes.
- Given A = [3, 2, 6] and B = [4, 1, 6], your function should return 0.
- Given A = [1, 4, 2, -2, 5] and B = [7, -2, -2, 2, 5], your function should return 2. The fair indexes are 2 and 4.
public class FairIndexCount {public int solution(int[] A, int[] B) {int sumA = 0;int sumB = 0;for (int i = 0; i < A.length; i++) {sumA += A[i];sumB += B[i];}int count = 0;int leftASum = A[0];int leftBSum = B[0];for (int k = 1; k < A.length; k++) {if (leftASum == leftBSum && leftBSum== (sumA-leftASum) && leftBSum == (sumB-leftBSum)) {count++;}leftASum += A[k];leftBSum += B[k];}return count;}public static void main(String[] args) {FairIndexCount fairIndexCount = new FairIndexCount();System.out.println(fairIndexCount.solution(new int[]{0, 4, -1, 0, 3}, new int[]{0, -2, 5, 0, 3})); // 2System.out.println(fairIndexCount.solution(new int[]{2, -2, -3, 3}, new int[]{0, 0, 4, -4})); // 1System.out.println(fairIndexCount.solution(new int[]{4, -1, 0, 3}, new int[]{-2, 6, 0, 4})); // 0System.out.println(fairIndexCount.solution(new int[]{3, 2, 6}, new int[]{4, 1, 6})); // 0System.out.println(fairIndexCount.solution(new int[]{1, 4, 2, -2, 5}, new int[]{7, -2, -2, 2, 5})); // 2}
}
这篇关于2022 Task 3 Fair Index Count的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!