Skip to content

Feature/max array sum #413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# [Dynamic Programming: Max Array Sum](https://www.hackerrank.com/challenges/max-array-sum)

- Difficulty: `#medium`
- Category: `#ProblemSolvingIntermediate`

## Sources

- [Max Array Sum — HackerRank Medium Using Inplace Dynamic Programming](https://iawale.medium.com/max-array-sum-hackerrank-medium-using-inplace-dynamic-programming-215a620d7705)
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# [Dynamic Programming: Max Array Sum](https://www.hackerrank.com/challenges/max-array-sum)

- Difficulty: `#medium`
- Category: `#ProblemSolvingIntermediate`

Given an array of integers, find the subset of
non-adjacent elements with the maximum sum.
Calculate the sum of that subset.
It is possible that the maximum sum is `0`, the case when all elements are negative.

## Example

`arr = [-2, 1, 3, -4, 5]`

The following subsets with more than element exist.
These exclude the empty subset and single element subsets which are also valid.

```text
Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] 6
[3, 5] 8
```

The maximum subset sum is . Note that any individual element is a subset as well.

`arr = [-2, -3, -1]`

In this case, it is best to choose no element: return `0`.

## Function Description

Complete the `maxSubsetSum` function in the editor below.

maxSubsetSum has the following parameter(s):

- `int arr[n]`: an array of integers

## Returns

- `int`: the maximum subset sum

## Input Format

The first line contains an integer, `n`.
The second line contains `n` space-separated integers `arr[i]`.

## Constraints

- $ 1 \leq n \leq 10^5 $
- $ -10^4 \leq arr[i] \leq 10^4 $

## Sample Input 0

```text
5
3 7 4 6 5
```

## Sample Output 0

```text
13
```

## Explanation 0

Our possible subsets are `[3, 4, 5]`. `[3, 4]`, `[3, 6]`, `[3, 5]`, `[7, 6]`,
`[7, 5]` and `[4, 5]`.
The largest subset sum is `13` from subset `[7, 6]`

## Sample Input 1

```text
5
2 1 5 8 4
```

## Sample Output 1

```text
11
```

## Explanation 1

Our subsets are `[2, 5, 4]`, `[2, 5]`, `[2, 8]`, `[2, 4]`, `[1, 8]`,
`[1, 4]` and `[5, 4]`.
The maximum subset sum is `11` from the first subset listed.

## Sample Input 2

```text
5
3 5 -7 8 10
```

## Sample Output 2

```text
15
```

## Explanation 2

Our subsets are `[3, -7, 10]`, `[3, 8]`, `[3,10]`, `[5, 8]`,
`[5, 10]` and `[-7, 10]`.

The maximum subset sum is `15` from the fifth subset listed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, expect, it } from '@jest/globals';
import { logger as console } from '../../../logger';

import { maxSubsetSum } from './max_array_sum';

import TEST_CASES from './max_array_sum.testcases.json';
import TEST_CASE3 from './max_array_sum.testcase3.json';

const ALL_TEST_CASES = [...TEST_CASES, TEST_CASE3];

const DECIMAL_RADIX = 10;

describe('max_array_sum', () => {
it('maxSubsetSum test cases', () => {
expect.assertions(4);

ALL_TEST_CASES.forEach((test) => {
const answer = maxSubsetSum(test.input).toString(DECIMAL_RADIX);

console.debug(`maxSubsetSum(${test.input}) solution found: ${answer}`);

expect(answer).toStrictEqual(test.expected);
});
});

it('maxSubsetSum edge case zero', () => {
expect.assertions(1);

const input: number[] = [];
const expected: number = 0;

const answer = maxSubsetSum(input);

console.debug(`maxSubsetSum(${input}) solution found: ${answer}`);

expect(answer).toStrictEqual(expected);
});

it('maxSubsetSum edge case one', () => {
expect.assertions(1);

const input: number[] = [1];
const expected: number = 1;

const answer = maxSubsetSum(input);

console.debug(`maxSubsetSum(${input}) solution found: ${answer}`);

expect(answer).toStrictEqual(expected);
});
});

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[
{
"title": "Sample Test case 0",
"input": [3, 7, 4, 6, 5],
"expected": "13"
},
{
"title": "Sample Test case 1",
"input": [2, 1, 5, 8, 4],
"expected": "11"
},
{
"title": "Sample Test case 2",
"input": [3, 5, -7, 8, 10],
"expected": "15"
}
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/dynamic_programming/max_array_sum.md]]
* @see Solution Notes: [[docs/hackerrank/interview_preparation_kit/dynamic_programming/max_array_sum-solution-notes.md]]
*/

const bigIntMax = (...args: bigint[]): bigint =>
args.reduce((m, e) => (e > m ? e : m), BigInt(0));

export function maxSubsetSum(arr: number[]): number {
const arrCopy: bigint[] = arr.map((x: number): bigint => BigInt(x));

if (arrCopy.length == 0) {
return 0;
}

const total = arrCopy.length;

if (total == 1) {
return Number(arrCopy[0]);
}

let t_max = bigIntMax(arrCopy[0], arrCopy[1]);
arrCopy[1] = t_max;

for (let i = 2; i < total; i++) {
t_max = bigIntMax(arrCopy[i - 2] + arrCopy[i], t_max);
t_max = bigIntMax(arrCopy[i], t_max);
arrCopy[i] = t_max;
}

return Number(t_max);
}

export default { maxSubsetSum };