Tech Tips

  1. Uncategorized
  2. 733 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

Uncategorized recent post

  1. Run Amazon FreeRTOS on M5Stack Core2 for AWS …

  2. Udacity Self-Driving Car Engineer Nanodegree …

  3. Install sbt 1.0.0 and run sample template

  4. Visualization of Neural Network and its Train…

  5. [Machine Learning]Created docker image includ…

関連記事

PAGE TOP