亚洲精品不卡AV在线播放|国产性爱无码高清视频|国产成人 ,97人人色,国产免费一区二区三区,日本一区二区在线

內(nèi)容中心

返回列表
2026年熱門的寧波水電氣自動(dòng)供料設(shè)計(jì)/水電氣自動(dòng)供料規(guī)劃怎么聯(lián)系供應(yīng)商推薦
2026-02-10 07:21:03

To solve this problem, we need to write a function that finds the maximum value in a slice of integers while handling edge cases such as empty slices appropriately.

Approach

The approach to find the maximum value in a slice involves the following steps:

  1. Check for Empty Slice: If the input slice is empty, return an error since there is no value to consider.
  2. Initialize Maximum Value: Start with the first element of the slice as the initial maximum value.
  3. Iterate Through Elements: Loop through the remaining elements of the slice. For each element, if it is greater than the current maximum value, update the maximum value.
  4. Return Result: After processing all elements, return the maximum value and a nil error (indicating success).

Solution Code

package main

import (
    "errors"
    "fmt"
)

// Max finds the maximum value in a slice of integers.
// Returns an error if the slice is empty.
func Max(slice []int) (int, error) {
    if len(slice) == 0 {
        return 0, errors.New("slice is empty")
    }
    max := slice[0]
    for _, num := range slice[1:] {
        if num > max {
            max = num
        }
    }
    return max, nil
}

func main() {
    // Test cases to verify the function
    testCases := [][]int{
        {3, 1, 4, 1, 5, 9, 2, 6}, // Positive numbers
        {-5, -3, -10},             // Negative numbers
        {7},                       // Single element
        {},                        // Empty slice
        {2, 2, 2},                 // All elements the same
    }

    for _, tc := range testCases {
        maxVal, err := Max(tc)
        if err != nil {
            fmt.Printf("Test case %v: Error: %v\n", tc, err)
        } else {
            fmt.Printf("Test case %v: Max value = %d\n", tc, maxVal)
        }
    }
}

Explanation

  • Empty Slice Handling: The function first checks if the slice length is zero. If so, it returns an error (slice is empty) and a default value of 0.
  • Initial Maximum: The initial maximum value is set to the first element of the slice (since the slice is non-empty at this point).
  • Iteration: The loop processes each element from the second position onwards. For each element, it compares with the current maximum and updates the maximum if the element is larger.
  • Test Cases: The main function includes test cases for various scenarios (positive numbers, negative numbers, single element, empty slice, all elements same) to validate the function's correctness.

Output

When you run the code, the output will be:

Test case [3 1 4 1 5 9 2 6]: Max value = 9
Test case [-5 -3 -10]: Max value = -3
Test case [7]: Max value =7
Test case []: Error: slice is empty
Test case [2 2 2]: Max value =2

This confirms that the function handles all edge cases correctly and efficiently. The time complexity of this function is O(n) where n is the length of the slice, as it processes each element exactly once. The space complexity is O(1) since it uses a fixed amount of additional space.



(免責(zé)聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進(jìn)行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點(diǎn)及立場(chǎng)。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責(zé)任歸材料提供方所有和承擔(dān)。本網(wǎng)站對(duì)此資訊文字、圖片等所有信息的真實(shí)性不作任何保證或承諾,亦不構(gòu)成任何購(gòu)買、投資等建議,據(jù)此操作者風(fēng)險(xiǎn)自擔(dān)。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請(qǐng)聯(lián)系原著作權(quán)人,如有侵權(quán),請(qǐng)聯(lián)系本網(wǎng)進(jìn)行刪除。

點(diǎn)擊呼叫(詳情介紹)
在線客服

在線留言
您好,很高興為您服務(wù),可以留下您的電話或微信嗎?