char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
int j = i + 1;
int end = j + targetCount - 1;
for (int k = targetOffset + 1; j < end && source[j] ==
target[k]; j++, k++);
if (j == end) {
/* Found whole string. */
return i - sourceOffset;
}
}
Asked
Active
Viewed 82 times
-1

nolawi
- 4,439
- 6
- 22
- 45
-
1No I am trying to get the maximum difference between the values as long as the smallest number is before the largest number. `max` wont work because the price starts at the highest number? I do not know of how to compare values in array? – nolawi May 20 '17 at 23:45
-
2Max profit would have been to short at 11 and cover at 1. ;-) Looks like a job for [*reduce*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). – RobG May 20 '17 at 23:52
-
@jfriend00 edited the question to remove efficient - let me know if this suffices If you disagree i will close the q! – nolawi May 20 '17 at 23:52
-
2I don't think this problem has anything to do with `.indexOf()` which your title seems to indicate you think you have to use. Is this a homework problem that requires the use of `.indexOf()`? – jfriend00 May 20 '17 at 23:59
-
@jfriend00 lol I dont have homework.. – nolawi May 21 '17 at 00:54
-
But the index matters as well – nolawi May 21 '17 at 00:55
1 Answers
4
This can be solved in O(n):
function getMaxProfit(prices) {
let min = prices[0];
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] < min)
min = prices[i];
if (prices[i] - min > profit)
profit = prices[i] - min;
}
return profit;
}
The idea is scan from start to end to get the best min before position i. This min is used to calculate the best profit you can get by selling on day i (immediately) and this amount is compared to the global (max) profit.

maraca
- 8,468
- 3
- 23
- 45