Production Level Knowledge & Tips

  1. 未分類
  2. 2 view

[Algorithm] Greedy Method

Target

greedy-ans1

Greedy Method

greedy

Apply Greedy Method To The Problem

greedy-ans2
greedy-ans3
greedy-ans4
greedy-ans5

Source Code

package main

import (
  "fmt"
  "bufio"
  "os"
  "strconv"
  "strings"
)

// Standard Input Function
func Scan() string {
  reader := bufio.NewReader(os.Stdin)
  input, _ := reader.ReadString('\n')
  return strings.TrimRight(input, "\n")
}

// Min
func Min(v1, v2 int) int {
  if v1 > v2 { return v2
  } else     { return v1 }
}

func Solve(amount int, values [6]int, limits []int) int {
  answer := 0

  for i := 5; i >= 0; i-- {
    num := Min(amount / values[i], limits[i])
    amount -= num * values[i]
    answer += num
  }

  return answer
}

func main() {
  coinValue := [6]int{1, 5, 10, 50, 100, 500}
  coinLimit := make([]int, 6)

  fmt.Printf("Please input total amount to pay:")
  amount,_ := strconv.Atoi(Scan())

  for i := 0; i < 6; i++ {
    fmt.Printf("Please input limit number of %d yen:", coinValue[i])
    coinLimit[i], _ = strconv.Atoi(Scan())
  }

  fmt.Printf("Answer : %d\n", Solve(amount, coinValue, coinLimit))
}

Result

Please input total amount to pay:620
Please input limit number of 1 yen:3
Please input limit number of 5 yen:2
Please input limit number of 10 yen:1
Please input limit number of 50 yen:3
Please input limit number of 100 yen:0
Please input limit number of 500 yen:2
Answer : 6

未分類 recent post

  1. Install sbt 1.0.0 and run sample template

  2. Visualization of Neural Network and its Train…

  3. [Machine Learning]Created docker image includ…

  4. [Node.js]How to write batch script with Node.…

  5. [Hive]Get top n items for each category

関連記事

PAGE TOP