はじめに
転職の内定が決まった。
しかし、ある会社でコーディングテストがあったが
全く歯が立たんかった。
克服したいので、NeetCodeを少しずつ進めていく。
ひとまずEasyのものから。
その際の回答に必要だった知識や気づきを書いていこうと思う。
挑戦した問題
問題の概要
You are given an integer array prices where prices[i] is the price of NeetCoin on the ith day.
You may choose a single day to buy one NeetCoin and choose a different day in the future to sell it.
Return the maximum profit you can achieve. You may choose to not make any transactions, in which case the profit would be 0.
Example
Input: prices = [10,1,5,6,7,1]
Output: 6
回答の流れ
- 配列の前から1日目,2日目...とする
- Loop
- 最大利益 と 現行の金額-最小購入金額 を比べ、大きいほうを新たな最大利益とする
- 最小購入金額 と 現行の金額 を比べ、小さいほうを最小購入金額とする
- End
- 最大利益を返す
回答のために必要だった知識
// 最大を探したい場合の初期値は0,最小を探したい場合の初期値は...
int maxP = 0;
int minBuy = prices[0];