본문 바로가기

Computer Science/Algorithm with Code

Hacker Rank_2/54 tests (Easy, Min-Max Sum)

While solving basic problems from the beginning, I should also practice summarizing problems written in English.

And plan to organize Swift grammar thoroughly starting from the basics.

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.


Using a removeAll(where:) is more readable than using a reversed filter() call because it specifies what you don’t want rather than what you want. It’s also more performant than filter() because it removes objects in place, and so avoids extra copying.

*Conditional statements - filter는 제할 시, 주로 사용  /  where은 선택 시, 주로 사용 (참고)

 

func miniMaxSum(arr: [Int]) -> Void {
    
    //var arr_copy = arr.map { $0 } // Deep copy, Not a Shallow

    let min_idx = arr.firstIndex{ $0 == arr.min() }
    let max_idx = arr.firstIndex{ $0 == arr.max() }

    var min_ans = 0
    var max_ans = 0
    
    for i in 0..<arr.count {
        if i != min_idx {
            min_ans += arr[i]
        }
        if i != max_idx {
            max_ans += arr[i]
        }
    }

    print(max_ans, min_ans)
}

 

// Mutating - New Instance를 할당하거나, Structure 내의 값 변경시 사용

// Closure - Parameter -> (Return Type) in Statements // Like Where

I will sort out these parts in more detail.


[References]

https://www.hackingwithswift.com/example-code/language/removing-matching-elements-from-a-collection-removeallwhere