Skip to content

Commit 221e281

Browse files
committed
feat: add profit targets in javascript
1 parent b6b520b commit 221e281

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

js/profit_targets.js

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-03-19 17:01:38
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-03-19 18:14:06
6+
*/
7+
8+
/**
9+
* 双指针法
10+
*
11+
* 金融分析师负责以一系列为代表的有利可图股票投资组合。每个的数组中的项目代表相应股票的年利润。
12+
* 分析师收集了所有达到目标利润的不同对股票。不同的对是至少不同的对一个元素。给定利润数组,
13+
* 找到不同一对股票的数量,其中每对的总和利润与目标利润完全相等。
14+
*
15+
* 示例 1:
16+
* 输入:
17+
* stocksProfit = [5, 7, 9, 13, 11, 6, 6, 3, 31]
18+
* target = 12 (利润目标)
19+
*
20+
* 输出:3
21+
* 因为存在 3 对股票组合的利润是 12:[5, 7],[3, 9],[6, 6]
22+
*
23+
*/
24+
25+
function stockPairs(stocksProfit, target) {
26+
let pairs = 0;
27+
let low = 0,
28+
high = stocksProfit.length - 1;
29+
30+
// 将数组排序
31+
stocksProfit.sort((a, b) => a - b);
32+
33+
while (low < high) {
34+
if (stocksProfit[low] + stocksProfit[high] === target) {
35+
// 移除重复元素
36+
while (low < high && stocksProfit[low] === stocksProfit[low + 1]) {
37+
low++;
38+
}
39+
while (
40+
low < high &&
41+
stocksProfit[high] === stocksProfit[high - 1]
42+
) {
43+
high--;
44+
}
45+
46+
pairs += 1;
47+
48+
low++;
49+
high--;
50+
} else if (stocksProfit[low] + stocksProfit[high] < target) {
51+
low++;
52+
} else {
53+
high--;
54+
}
55+
}
56+
57+
return pairs;
58+
}
59+
60+
console.log("====================================");
61+
console.log(stockPairs([5, 6, 5, 7, 7, 8], 13)); // 输出 2
62+
console.log("====================================");
63+
64+
console.log("====================================");
65+
console.log(stockPairs([5, 7, 9, 13, 11, 6, 6, 3, 31], 12)); // 输出 3
66+
console.log("====================================");

0 commit comments

Comments
 (0)