Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

algorithm - interviewstreet Triplet challenge

There is an integer array d which does not contain more than two elements of the same value. How many distinct ascending triples (d[i] < d[j] < d[k], i < j < k) are present?

Input format:

The first line contains an integer N denoting the number of elements in the array. This is followed by a single line containing N integers separated by a single space with no leading/trailing spaces

Output format:

A single integer that denotes the number of distinct ascending triples present in the array

Constraints:

N <= 10^5 Every value in the array is present at most twice Every value in the array is a 32-bit positive integer

Sample input:

6 
1 1 2 2 3 4

Sample output:

4

Explanation:

The distinct triplets are

(1,2,3)
(1,2,4)
(1,3,4)
(2,3,4)

Another test case:

Input:

10
1 1 5 4 3 6 6 5 9 10

Output:

28

I tried to solve using DP. But out of 15 test cases only 7 test cases passed. Please help solve this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should note that you only need to know the number of elements that are smaller/larger than a particular element to know how many triples it serves as the middle point for. Using this you can calculate the number of triples quite easily, the only remaining problem is to get rid of duplicates, but given that you are limited to at most 2 of the same element, this is trivial.

I solved using a Binary Index Tree http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees.

I also did a small write up, http://www.kesannmcclean.com/?p=223.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...