[LeetCode] 121. Best Time to Buy and Sell Stock

Easy
Related Topics: Array / Dynamic Programming
LeetCode Source

解题想法

当下想到最直觉的解法,一个变数 min_index 纪录最小值的位置,i 用来寻访每个的 prices 的值

for loop 里头判断式用来找寻最佳解

if prices[i] < prices[min_index] 找寻最小值得位置if i > min_index and prices[i] - prices[min_index] > resres 最佳解

Python

class Solution:    def maxProfit(self, prices: List[int]) -> int:        min_index, res = 0, 0        for i in range(1, len(prices)):            if prices[i] < prices[min_index]:                min_index = i            if i > min_index and prices[i] - prices[min_index] > res:                res = prices[i] - prices[min_index]        return res

C++

class Solution {public:    int maxProfit(vector<int>& prices) {        int res = 0, min_index = 0;        for (int i = 1; i < prices.size(); i++) {            if (prices[i] < prices[min_index])                min_index = i;            if (i > min_index && prices[i] - prices[min_index] > res)                res = prices[i] - prices[min_index];        }        return res;    }};

这系列文被记录在 Top Interview 150 Series


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章