# SmallSum

Algorithmic problem 专栏收录该内容
3 篇文章 0 订阅

# [Question]

## [Example]

int[] array = new int[] {1, 3, 4, 2, 5};
smallSum = 1 + (1 + 3) + 1 + (1 + 3 + 4 + 2) //==> smallSum = 16


## [Idea]

将小和问题转换为右边有多少个数比它大（基于MergeSort）


# [Source code]

public class code02_SmallSum {
public static void main(String[] args) {
System.out.println(smallSum(new int[]{1, 3, 4, 2, 5}));
}

public static int smallSum(int[] array) {
if (array == null || array.length < 2) {
return 0;
}
return process(array, 0, array.length - 1);
}

public static int process(int[] array, int L, int R) {
if (L == R) {
return 0;
}
int middle = L + ((R - L) >> 1);
return process(array, L, middle) + process(array, middle + 1, R) + merge(array, L, middle, R);
}

public static int merge(int[] array, int L, int middle, int R) {
int[] tmp = new int[R - L + 1];
int i = 0;
int p1 = L;
int p2 = middle + 1;
int sum = 0;
while (p1 <= middle && p2 <= R) {
sum += array[p1] < array[p2] ? array[p1] * (R - p2 + 1) : 0;
tmp[i++] = array[p1] < array[p2] ? array[p1++] : array[p2++];
}
while (p1 <= middle) {
tmp[i++] = array[p1++];
}
while (p2 <= R) {
tmp[i++] = array[p2++];
}
System.arraycopy(tmp, 0, array, L, tmp.length);
return sum;
}
}

• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报