Sum of array elements

This problem asks you to return the sum of the elements in an array of integers. For example, given the input array [1, 2, 3, 4, 5], the output would be 15 (1 + 2 + 3 + 4 + 5 = 15).

Problem

Given an array of integers, return the sum of the elements in the array.
Example input: [1, 2, 3, 4, 5]
Example output: 15

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

int sum(vector<int> arr) {
    int sum = 0;
    for (int i = 0; i < arr.size(); i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    vector<int> arr = {1, 2, 3, 4, 5};
    cout << sum(arr) << endl;
    return 0;
}

/*

This solution is optimal because it is O(n) time complexity.

*/

A.I. Evaluation of the Solution

This solution is correct and solves the problem. The approach is also optimal, as it has a time complexity of O(n).

Evaluated at: 2022-12-01 06:15:32