Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de796d4

Browse files
Create 3652-best-time-to-buy-and-sell-stock-using-strategy.js
1 parent fb715fb commit de796d4

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {number[]} prices
3+
* @param {number[]} strategy
4+
* @param {number} k
5+
* @return {number}
6+
*/
7+
var maxProfit = function(prices, strategy, k) {
8+
let a = 0,
9+
b = 0,
10+
c = 0
11+
12+
function calc(arr) {
13+
let res = 0
14+
for (let i = 0; i < prices.length; i++) {
15+
res += prices[i] * arr[i]
16+
}
17+
return res
18+
}
19+
20+
const n = strategy.length
21+
const base = calc(strategy)
22+
const h = Math.floor(k / 2)
23+
const A = strategy.map((s, i) => -s * prices[i])
24+
const B = strategy.map((s, i) => (1 - s) * prices[i])
25+
const pA = new Array(n + 1).fill(0)
26+
const pB = new Array(n + 1).fill(0)
27+
28+
for (let i = 0; i < n; i++) {
29+
pA[i + 1] = pA[i] + A[i]
30+
pB[i + 1] = pB[i] + B[i]
31+
}
32+
33+
let res = 0
34+
for (let i = 0; i <= n - k; i++) {
35+
const first = pA[i + h] - pA[i]
36+
const second = pB[i + k] - pB[i + h]
37+
const d = first + second
38+
res = Math.max(d, res)
39+
}
40+
41+
return base + res
42+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /